answer
stringlengths 17
10.2M
|
|---|
package io.getlime.security.powerauth.app.nextstep.repository.model.entity;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.ToString;
import javax.persistence.*;
import java.io.Serializable;
import java.util.Date;
/**
* Entity which stores AFS requests and responses.
*
* @author Roman Strobl, roman.strobl@wultra.com
*/
@Entity
@Table(name = "ns_operation_afs")
@Data
@EqualsAndHashCode(of = {"afsAction", "stepIndex", "timestampCreated", "operation"})
public class OperationAfsActionEntity implements Serializable {
private static final long serialVersionUID = 744614077188309148L;
@Id
@SequenceGenerator(name = "ns_operation_afs", sequenceName = "ns_operation_afs_seq")
@GeneratedValue(strategy = GenerationType.AUTO, generator = "ns_operation_afs")
@Column(name = "afs_action_id", nullable = false)
private Long afsActionId;
@Column(name = "request_afs_action", nullable = false)
private String afsAction;
@Column(name = "request_step_index", nullable = false)
private int stepIndex;
@Column(name = "request_afs_extras")
private String requestAfsExtras;
@Column(name = "response_afs_apply", nullable = false)
private boolean afsResponseApplied;
@Column(name = "response_afs_label")
private String afsLabel;
@Column(name = "response_afs_extras")
private String responseAfsExtras;
@Column(name = "timestamp_created", nullable = false)
private Date timestampCreated;
@ToString.Exclude
@ManyToOne
@JoinColumn(name = "operation_id", referencedColumnName = "operation_id", updatable = false, nullable = false)
private OperationEntity operation;
}
|
package xyz.brassgoggledcoders.steamagerevolution.modules.steam.tileentities.multiblock.furnace;
import java.util.HashSet;
import java.util.Set;
import com.teamacronymcoders.base.multiblock.IMultiblockPart;
import com.teamacronymcoders.base.multiblock.validation.IMultiblockValidator;
import com.teamacronymcoders.base.util.ItemStackUtils;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.World;
import net.minecraftforge.fluids.Fluid;
import net.minecraftforge.fluids.FluidTank;
import net.minecraftforge.items.ItemHandlerHelper;
import net.minecraftforge.items.ItemStackHandler;
import xyz.brassgoggledcoders.steamagerevolution.modules.steam.tileentities.multiblock.RectangularMultiblockController;
import xyz.brassgoggledcoders.steamagerevolution.modules.steam.tileentities.multiblock.turbine.TileEntitySteamInput;
public class SteamFurnaceController extends RectangularMultiblockController {
private Set<TileEntityFurnaceItemInput> attachedItemInputs;
private Set<TileEntityFurnaceItemOutput> attachedItemOutputs;
private Set<TileEntityFurnaceSteamInput> attachedSteamInputs;
public ItemStackHandler inputInventory;
public ItemStackHandler outputInventory;
public FluidTank steamTank;
int temperature = 0;
private float pressure = 0;
private int fluidUseOnHeat = 1000;
private int fluidUseOnUpkeep = 100;
public SteamFurnaceController(World world) {
super(world);
attachedItemInputs = new HashSet<TileEntityFurnaceItemInput>();
attachedItemOutputs = new HashSet<TileEntityFurnaceItemOutput>();
attachedSteamInputs = new HashSet<TileEntityFurnaceSteamInput>();
inputInventory = new ItemStackHandler(3);
outputInventory = new ItemStackHandler(3);
steamTank = new FluidTank(0);
}
@Override
protected void onBlockAdded(IMultiblockPart newPart) {
if(newPart instanceof TileEntityFurnaceItemInput) {
attachedItemInputs.add((TileEntityFurnaceItemInput) newPart);
}
else if(newPart instanceof TileEntityFurnaceItemOutput) {
attachedItemOutputs.add((TileEntityFurnaceItemOutput) newPart);
}
else if(newPart instanceof TileEntityFurnaceSteamInput) {
attachedSteamInputs.add((TileEntityFurnaceSteamInput) newPart);
steamTank = new FluidTank(steamTank.getFluid(), Fluid.BUCKET_VOLUME * 16 * attachedSteamInputs.size());
}
super.onBlockAdded(newPart);
}
@Override
protected void onBlockRemoved(IMultiblockPart oldPart) {
if(oldPart instanceof TileEntityFurnaceItemInput) {
attachedItemInputs.remove(oldPart);
}
else if(oldPart instanceof TileEntityFurnaceItemOutput) {
attachedItemOutputs.remove(oldPart);
}
else if(oldPart instanceof TileEntitySteamInput) {
attachedSteamInputs.add((TileEntityFurnaceSteamInput) oldPart);
steamTank = new FluidTank(steamTank.getFluid(), (Fluid.BUCKET_VOLUME * 16) * attachedSteamInputs.size());
}
super.onBlockRemoved(oldPart);
}
@Override
protected boolean updateServer() {
super.updateServer();
if(temperature < 200) {
if(steamTank.getFluid() != null && steamTank.drain(fluidUseOnHeat, false).amount == fluidUseOnHeat) {
steamTank.drain(fluidUseOnHeat, true);
temperature++;
return true;
}
}
else {
if(steamTank.getFluid() != null && steamTank.drain(fluidUseOnUpkeep, false).amount == fluidUseOnUpkeep) {
steamTank.drain(fluidUseOnUpkeep, true);
}
else {
temperature
}
return true;
}
if(temperature >= 80) {
for(int i = 0; i < inputInventory.getSlots(); i++) {
if(ItemStackUtils.isItemNonNull(inputInventory.getStackInSlot(i)) && ItemStackUtils.isItemNonNull(
SteamFurnaceRecipes.instance().getResult(inputInventory.getStackInSlot(i), temperature))) {
ItemStack r =
SteamFurnaceRecipes.instance().getResult(inputInventory.getStackInSlot(i), temperature);
ItemStack resultItem = new ItemStack(r.getItem(), 1, r.getItemDamage());
if(ItemHandlerHelper.insertItem(outputInventory, resultItem, true) == null) {
if(inputInventory.extractItem(i, resultItem.stackSize, true) != null) {
inputInventory.extractItem(i, resultItem.stackSize, false);
ItemHandlerHelper.insertItem(outputInventory, resultItem, false);
return true;
}
}
}
}
}
return false;
}
@Override
protected boolean isBlockGoodForInterior(World world, int x, int y, int z, IMultiblockValidator validatorCallback) {
if(world.isAirBlock(new BlockPos(x, y, z)))
return true;
else
return false;
}
@Override
protected int getMinimumNumberOfBlocksForAssembledMachine() {
return 26;
}
@Override
protected int getMinimumXSize() {
return 3;
}
@Override
protected int getMinimumZSize() {
return 3;
}
@Override
protected int getMinimumYSize() {
return 3;
}
@Override
protected int getMaximumXSize() {
return 6;
}
@Override
protected int getMaximumZSize() {
return 6;
}
@Override
protected int getMaximumYSize() {
return 6;
}
@Override
public void readFromDisk(NBTTagCompound data) {
temperature = data.getInteger("temperature");
inputInventory.deserializeNBT(data.getCompoundTag("inputinv"));
outputInventory.deserializeNBT(data.getCompoundTag("outputinv"));
steamTank.readFromNBT(data.getCompoundTag("fluidtank"));
super.readFromDisk(data);
}
@Override
public void writeToDisk(NBTTagCompound data) {
data.setInteger("temperature", temperature);
data.setTag("inputinv", inputInventory.serializeNBT());
data.setTag("outputinv", outputInventory.serializeNBT());
NBTTagCompound tankTag = new NBTTagCompound();
steamTank.writeToNBT(tankTag);
data.setTag("fluidtank", tankTag);
super.writeToDisk(data);
}
}
|
package org.xwiki.security.authorization;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.apache.commons.lang3.builder.EqualsBuilder;
import org.xwiki.model.EntityType;
import static org.xwiki.security.SecurityReference.FARM;
import static org.xwiki.security.authorization.RuleState.ALLOW;
import static org.xwiki.security.authorization.RuleState.DENY;
import static org.xwiki.security.authorization.RuleState.UNDETERMINED;
/**
* Enumeration of the possible rights.
* @version $Id$
* @since 4.0M2
*/
public class Right implements RightDescription, Serializable, Comparable<Right>
{
/** The login access right. */
public static final Right LOGIN;
/** The view access right. */
public static final Right VIEW;
/** The edit access right. */
public static final Right EDIT;
/** The delete access right. */
public static final Right DELETE;
/** Imply rights provided to creator of a document. */
public static final Right CREATOR;
/** The Admin access right. */
public static final Right ADMIN;
/** The program access right. */
public static final Right PROGRAM;
/** The script access right. */
public static final Right SCRIPT;
/** The register access right. */
public static final Right REGISTER;
/** The comment access right. */
public static final Right COMMENT;
/** The creation of a Wiki right. */
public static final Right CREATE_WIKI;
public static final Right ILLEGAL;
public static final String ILLEGAL_RIGHT_NAME = "illegal";
/** Targeted entity type list to target only the main wiki. */
public static final Set<EntityType> FARM_ONLY = null;
/** Targeted entity type list to target only wikis (including main wiki). */
public static final Set<EntityType> WIKI_ONLY = EnumSet.of(EntityType.WIKI);
/** Targeted entity type list to target wikis and spaces. */
public static final Set<EntityType> WIKI_SPACE = EnumSet.of(EntityType.WIKI, EntityType.SPACE);
/** Targeted entity type list to target wikis, spaces and documents. */
public static final Set<EntityType> WIKI_SPACE_DOCUMENT
= EnumSet.of(EntityType.WIKI, EntityType.SPACE, EntityType.DOCUMENT);
/** Serialization identifier. */
private static final long serialVersionUID = 1L;
/** Internal list of existing instances. */
private static final List<Right> VALUES = new ArrayList<Right>();
/** Unmodifiable list of existing instance for public dissemination. */
private static final List<Right> UNMODIFIABLE_VALUES = Collections.unmodifiableList(VALUES);
/** List of all rights, as strings. */
private static final List<String> ALL_RIGHTS = new LinkedList<String>();
/** List of all rights, as strings. */
private static final List<String> UNMODIFIABLE_ALL_RIGHTS = Collections.unmodifiableList(ALL_RIGHTS);
/**
* The enabled rights by entity types. There is a special case hardcoded : The PROGRAM
* right should only be enabled for the main wiki, not for wikis in general.
*/
private static final Map<EntityType, Set<Right>> ENABLED_RIGHTS = new HashMap<EntityType, Set<Right>>();
/**
* The enabled rights by entity types, but with unmodifiable list for getters.
*/
private static final Map<EntityType, Set<Right>> UNMODIFIABLE_ENABLED_RIGHTS
= new HashMap<EntityType, Set<Right>>();
// @formatter:off
static {
LOGIN = new Right("login", ALLOW, ALLOW, true, null, WIKI_ONLY , true);
VIEW = new Right("view", ALLOW, DENY, true, null, WIKI_SPACE_DOCUMENT , true);
EDIT = new Right("edit", ALLOW, DENY, true,
new RightSet(VIEW), WIKI_SPACE_DOCUMENT , false);
DELETE = new Right("delete", DENY, DENY, true, null, WIKI_SPACE_DOCUMENT , false);
CREATOR = new Right("creator", DENY, ALLOW, false,
new RightSet(DELETE), EnumSet.of(EntityType.DOCUMENT), false);
REGISTER = new Right("register", ALLOW, ALLOW, true, null, WIKI_ONLY , false);
COMMENT = new Right("comment", ALLOW, DENY, true, null, WIKI_SPACE_DOCUMENT , false);
SCRIPT = new Right("script", DENY, DENY, true, null, WIKI_SPACE_DOCUMENT , true);
ADMIN = new Right("admin", DENY, ALLOW, false,
new RightSet(LOGIN, VIEW, SCRIPT, EDIT, DELETE, REGISTER, COMMENT), WIKI_SPACE , true);
CREATE_WIKI = new Right("createwiki", DENY, DENY, true, null, FARM_ONLY , false);
PROGRAM = new Right("programming", DENY, ALLOW, false,
new RightSet(LOGIN, VIEW, SCRIPT, EDIT, DELETE, REGISTER, COMMENT, ADMIN, CREATE_WIKI), FARM_ONLY, true);
ILLEGAL = new Right(ILLEGAL_RIGHT_NAME, DENY, DENY, false, null, null , false);
}
// @formatter:on
/** The numeric value of this access right. */
private final int value;
/** The string representation. */
private final String name;
/** The string representation. */
private final RuleState defaultState;
/** Whether this right should be allowed or denied in case of a tie. */
private final RuleState tieResolutionPolicy;
/** Policy on how this right should be overridden by lower levels. */
private final boolean inheritanceOverridePolicy;
/** Additional rights implied by this right. */
private final Set<Right> impliedRights;
/** Additional rights implied by this right. */
private final boolean isReadOnly;
/**
* Construct a new Right from its description.
* This is a package private constructor, the registration of a new right should be done using
* the {@link AuthorizationManager}
*
* @param description Description of the right to create.
*/
Right(RightDescription description)
{
this(description.getName(), description.getDefaultState(), description.getTieResolutionPolicy(),
description.getInheritanceOverridePolicy(),
description.getImpliedRights(),
description.getTargetedEntityType(), description.isReadOnly());
}
/**
* Construct a new Right.
* @param name The string representation of this right.
* @param defaultState The default state, in case no matching right is found at any level.
* @param tieResolutionPolicy Whether this right should be allowed or denied in case of a tie.
* @param inheritanceOverridePolicy Policy on how this right should be overridden by lower levels.
* @param impliedRights Additional rights implied by this right.
* @param validEntityTypes The type of entity where this right should be enabled.
* @param isReadOnly If true, this right could be allowed when the wiki is in read-only mode.
*/
private Right(String name, RuleState defaultState, RuleState tieResolutionPolicy,
boolean inheritanceOverridePolicy, Set<Right> impliedRights, Set<EntityType> validEntityTypes,
boolean isReadOnly)
{
checkIllegalArguments(name, defaultState, tieResolutionPolicy);
this.name = name;
this.defaultState = defaultState;
this.tieResolutionPolicy = tieResolutionPolicy;
this.inheritanceOverridePolicy = inheritanceOverridePolicy;
this.impliedRights = cloneImpliedRights(impliedRights);
this.isReadOnly = isReadOnly;
synchronized (VALUES) {
this.value = VALUES.size();
if (this.value >= 64) {
throw new IndexOutOfBoundsException();
}
VALUES.add(this);
if (!name.equals(ILLEGAL_RIGHT_NAME)) {
ALL_RIGHTS.add(name);
}
if (validEntityTypes != null) {
for (EntityType type : validEntityTypes) {
if (type == EntityType.WIKI) {
// If enabled on a wiki, enable also on main wiki.
enableFor(FARM);
}
enableFor(type);
}
} else {
// If enabled on a wiki, enable also on main wiki.
enableFor(FARM);
}
}
}
/**
* Enable this right for the given entity type.
* @param type the entity type, null for the the main wiki.
*/
private void enableFor(EntityType type)
{
Set<Right> rights = ENABLED_RIGHTS.get(type);
if (rights == null) {
rights = new RightSet();
ENABLED_RIGHTS.put(type, rights);
UNMODIFIABLE_ENABLED_RIGHTS.put(type, Collections.unmodifiableSet(rights));
}
rights.add(this);
}
private void checkIllegalArguments(String name, RuleState defaultState, RuleState tieResolutionPolicy)
{
if (name == null || ALL_RIGHTS.contains(name) || (ILLEGAL != null && name.equals(ILLEGAL_RIGHT_NAME))) {
throw new IllegalArgumentException(String.format("Duplicate name for right [%s]", name));
}
if (defaultState == null || defaultState == UNDETERMINED) {
throw new IllegalArgumentException(
String.format("Invalid default state [%s] for right [%s]", defaultState, name));
}
if (tieResolutionPolicy == null || tieResolutionPolicy == UNDETERMINED) {
throw new IllegalArgumentException(
String.format("Invalid tie resolution policy [%s] for right [%s]", tieResolutionPolicy, name));
}
}
/**
* Clone implied Rights.
* @param impliedRights the collection of rights to clone.
* @return the cloned collection or null if no valid implied right has been provided.
*/
private Set<Right> cloneImpliedRights(Set<Right> impliedRights)
{
if (impliedRights == null || impliedRights.size() == 0) {
return null;
}
Set<Right> implied = new RightSet(impliedRights);
if (implied.size() > 0) {
return Collections.unmodifiableSet(implied);
} else {
return null;
}
}
/**
* @return an unmodifiable list of available Right
*/
public static List<Right> values()
{
return UNMODIFIABLE_VALUES;
}
public static Right toRight(String string)
{
for (Right right : VALUES) {
if (right.name.equals(string)) {
return right;
}
}
return ILLEGAL;
}
/**
* Returns the list of rights available for a given entity type.
*
* @param entityType the entity type, or null for main wiki.
* @return a list of {@code Right} enabled of this entity type
*/
public static Set<Right> getEnabledRights(EntityType entityType)
{
return UNMODIFIABLE_ENABLED_RIGHTS.get(entityType);
}
/**
* Retrieve a right based on its ordinal.
* @param ordinal the ordinal of the right
* @return the {@code Right}
*/
public static Right get(int ordinal) {
return VALUES.get(ordinal);
}
/**
* @return the count of all existing rights
*/
public static int size() {
return values().size();
}
/**
* @return a list of the string representation of all valid rights.
*/
public static List<String> getAllRightsAsString()
{
return UNMODIFIABLE_ALL_RIGHTS;
}
/**
* @return The numeric value of this access right.
*/
public int ordinal()
{
return value;
}
@Override
public String getName()
{
return name;
}
@Override
public String toString()
{
return getName();
}
@Override
public Set<Right> getImpliedRights()
{
return impliedRights;
}
@Override
public Set<EntityType> getTargetedEntityType()
{
List<EntityType> levels = new ArrayList<EntityType>();
for (Map.Entry<EntityType, Set<Right>> entry : ENABLED_RIGHTS.entrySet()) {
if (entry.getValue().contains(this)) {
levels.add(entry.getKey());
}
}
if (levels.contains(null) && levels.contains(EntityType.WIKI)) {
levels.remove(null);
} else {
return null;
}
return EnumSet.copyOf(levels);
}
@Override
public boolean getInheritanceOverridePolicy()
{
return inheritanceOverridePolicy;
}
@Override
public RuleState getTieResolutionPolicy()
{
return tieResolutionPolicy;
}
@Override
public RuleState getDefaultState()
{
return this.defaultState;
}
@Override
public boolean isReadOnly()
{
return this.isReadOnly;
}
@Override
public int compareTo(Right other)
{
return this.ordinal() - other.ordinal();
}
/**
* @param description a right description to compare this right to.
* @return true if the right is equivalent to the provided description.
*/
boolean like(RightDescription description)
{
return new EqualsBuilder()
.append(this.isReadOnly(), description.isReadOnly())
.append(this.getDefaultState(), description.getDefaultState())
.append(this.getTieResolutionPolicy(), description.getTieResolutionPolicy())
.append(this.getInheritanceOverridePolicy(), description.getInheritanceOverridePolicy())
.append(this.getTargetedEntityType(), description.getTargetedEntityType())
.append(this.getImpliedRights(), description.getImpliedRights())
.isEquals();
}
}
|
package edu.pitt.apollo.apolloservice.thread;
import edu.pitt.apollo.ApolloServiceConstants;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.math.BigInteger;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.channels.Channels;
import java.nio.channels.ReadableByteChannel;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.List;
import java.util.Random;
import java.util.Scanner;
import edu.pitt.apollo.GlobalConstants;
import edu.pitt.apollo.apollo_service_types.v3_0_0.RunSimulationsMessage;
import edu.pitt.apollo.apolloservice.error.ApolloServiceErrorHandler;
import edu.pitt.apollo.apolloservice.exception.BatchException;
import edu.pitt.apollo.apolloservice.methods.run.RunMethod;
import edu.pitt.apollo.apolloservice.methods.run.RunMethodForSimulationAndVisualization;
import edu.pitt.apollo.apolloservice.methods.run.RunResultAndSimulationGroupId;
import edu.pitt.apollo.apolloservice.translatorservice.TranslatorServiceAccessor;
import edu.pitt.apollo.db.ApolloDbUtils;
import edu.pitt.apollo.db.exceptions.ApolloDatabaseException;
import edu.pitt.apollo.db.exceptions.ApolloDatabaseKeyNotFoundException;
import edu.pitt.apollo.service.simulatorservice.v3_0_0.SimulatorServiceEI;
import edu.pitt.apollo.service.simulatorservice.v3_0_0.SimulatorServiceV300;
import edu.pitt.apollo.services_common.v3_0_0.ApolloSoftwareTypeEnum;
import edu.pitt.apollo.services_common.v3_0_0.Authentication;
import edu.pitt.apollo.services_common.v3_0_0.MethodCallStatusEnum;
import edu.pitt.apollo.services_common.v3_0_0.RunResult;
import edu.pitt.apollo.services_common.v3_0_0.SoftwareIdentification;
import edu.pitt.apollo.simulator_service_types.v3_0_0.RunSimulationMessage;
import edu.pitt.apollo.types.v3_0_0.FixedDuration;
import edu.pitt.apollo.types.v3_0_0.InfectionAcquisitionFromInfectiousHost;
import edu.pitt.apollo.types.v3_0_0.InfectionStateEnum;
import edu.pitt.apollo.types.v3_0_0.PopulationInfectionAndImmunityCensusDataCell;
import edu.pitt.apollo.types.v3_0_0.ReproductionNumber;
import edu.pitt.apollo.types.v3_0_0.UnitOfTimeEnum;
import java.sql.SQLException;
import javax.xml.ws.WebServiceException;
import org.apache.cxf.endpoint.Client;
import org.apache.cxf.frontend.ClientProxy;
import org.apache.cxf.transport.http.HTTPConduit;
import org.apache.cxf.transports.http.configuration.HTTPClientPolicy;
public class RunSimulationsThread extends RunApolloServiceThread {
private static final String FILE_NAME_FOR_INPUTS_WITH_RUN_IDS = "batch_inputs_with_run_ids.txt";
private static final SoftwareIdentification brokerServiceSoftwareId;
private static final int BROKER_SERVICE_SOFTWARE_ID_KEY;
Exception error = null;
private final RunSimulationsMessage message;
BigInteger simulationGroupId;
private URL configFileUrl;
private Authentication authentication;
public static final Random rng = new Random(System.currentTimeMillis());
private class BatchConfigRecord {
Double r0;
Double infectiousPeriod;
Double latentPeriod;
Double percentSusceptible;
Double percentExposed;
Double percentInfectious;
Double percentRecovered;
public BatchConfigRecord(String[] columns) {
percentSusceptible = Double.valueOf(columns[0]);
percentExposed = Double.valueOf(columns[1]);
percentInfectious = Double.valueOf(columns[2]);
percentRecovered = Double.valueOf(columns[3]);
r0 = Double.valueOf(columns[4]);
latentPeriod = Double.valueOf(columns[5]);
infectiousPeriod = Double.valueOf(columns[6]);
}
}
public static boolean isNonErrorCachedStatus(
MethodCallStatusEnum methodCallStatusEnum) {
switch (methodCallStatusEnum) {
case AUTHENTICATION_FAILURE:
case FAILED:
case UNAUTHORIZED:
case UNKNOWN_RUNID:
return false;
default:
return true;
}
}
public static String getRandomFilenameString() {
MessageDigest md5;
try {
md5 = MessageDigest.getInstance("MD5");
String time = ((Long) System.currentTimeMillis()).toString();
String rnd = ((Long) rng.nextLong()).toString();
String toHash = time + rnd;
md5.update(toHash.getBytes());
String filename = new BigInteger(1, md5.digest()).toString(16);
File f = new File(ApolloServiceConstants.APOLLO_DIR + "tmp");
f.mkdirs();
filename = ApolloServiceConstants.APOLLO_DIR + "tmp" + File.separator + filename + ".txt";
return filename;
} catch (NoSuchAlgorithmException e) {
// This is not likely to happen as MD5 isn't going anywhere.
return null;
}
}
public static synchronized File getTemporaryFile() {
File f = new File(getRandomFilenameString());
if (f.exists()) {
while (f.exists()) {
f = new File(getRandomFilenameString());
}
}
return f;
}
public static String downloadUrlToFile(URL configFileUrl)
throws BatchException, IOException {
ReadableByteChannel rbc;
try {
rbc = Channels.newChannel(configFileUrl.openStream());
File storageFile = getTemporaryFile();
if (storageFile != null) {
FileOutputStream fos = new FileOutputStream(storageFile);
fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);
fos.close();
return storageFile.getAbsolutePath();
} else {
throw new BatchException(
"Unable to create temporary storage file for the batch processing.");
}
} catch (IOException e) {
throw new IOException("Error downloading URL:" + configFileUrl
+ ". Error was: " + e.getMessage(), e);
}
}
public static RunSimulationMessage populateTemplateWithRecord(
RunSimulationsMessage template, BatchConfigRecord batchConfigRecord) {
RunSimulationMessage runSimulationMessage = new RunSimulationMessage();
runSimulationMessage.setAuthentication(template.getAuthentication());
runSimulationMessage.setInfectiousDiseaseScenario(template
.getBaseInfectiousDiseaseScenario());
runSimulationMessage.setSimulatorIdentification(template
.getSimulatorIdentification());
runSimulationMessage.setSimulatorTimeSpecification(template
.getSimulatorTimeSpecification());
ReproductionNumber r0 = new ReproductionNumber();
r0.setExactValue(batchConfigRecord.r0);
FixedDuration latentPeriod = new FixedDuration();
latentPeriod.setValue(batchConfigRecord.latentPeriod);
latentPeriod.setUnitOfTime(UnitOfTimeEnum.DAY);
FixedDuration infectiousPeriod = new FixedDuration();
infectiousPeriod.setValue(batchConfigRecord.infectiousPeriod);
infectiousPeriod.setUnitOfTime(UnitOfTimeEnum.DAY);
InfectionAcquisitionFromInfectiousHost infection = runSimulationMessage
.getInfectiousDiseaseScenario().getInfections().get(0)
.getInfectionAcquisitionsFromInfectiousHosts().get(0);
infection.setLatentPeriodDuration(latentPeriod);
infection.setInfectiousPeriodDuration(infectiousPeriod);
infection.getBasicReproductionNumbers().set(0, r0);
List<PopulationInfectionAndImmunityCensusDataCell> censusDataCells = runSimulationMessage
.getInfectiousDiseaseScenario()
.getPopulationInfectionAndImmunityCensuses().get(0)
.getCensusData().getCensusDataCells();
censusDataCells.clear();
censusDataCells.add(createPiiDataCell(InfectionStateEnum.SUSCEPTIBLE,
batchConfigRecord.percentSusceptible));
censusDataCells.add(createPiiDataCell(InfectionStateEnum.LATENT,
batchConfigRecord.percentExposed));
censusDataCells.add(createPiiDataCell(InfectionStateEnum.INFECTIOUS,
batchConfigRecord.percentInfectious));
censusDataCells.add(createPiiDataCell(InfectionStateEnum.RECOVERED,
batchConfigRecord.percentRecovered));
return runSimulationMessage;
}
private static PopulationInfectionAndImmunityCensusDataCell createPiiDataCell(
InfectionStateEnum infectionStateEnum, Double fractionInState) {
PopulationInfectionAndImmunityCensusDataCell piiDataCell = new PopulationInfectionAndImmunityCensusDataCell();
piiDataCell.setFractionInState(fractionInState);
piiDataCell.setInfectionState(infectionStateEnum);
return piiDataCell;
}
public void queueAndTranslateRuns() {
String filename = null;
SoftwareIdentification simulatorIdentification = message
.getSimulatorIdentification();
try {
try {
filename = downloadUrlToFile(configFileUrl);
} catch (BatchException ex) {
ApolloServiceErrorHandler.writeErrorToErrorFile(
"Error downloading batch configuration file, error was: "
+ simulatorIdentification.getSoftwareName()
+ ", version: "
+ simulatorIdentification.getSoftwareVersion()
+ ", developer: "
+ simulatorIdentification
.getSoftwareDeveloper()
+ " for run id " + runId + ": "
+ ex.getMessage(), runId);
return;
} catch (IOException ex) {
ApolloServiceErrorHandler.writeErrorToErrorFile(
"Error downloading batch configuration file, error was: "
+ simulatorIdentification.getSoftwareName()
+ ", version: "
+ simulatorIdentification.getSoftwareVersion()
+ ", developer: "
+ simulatorIdentification
.getSoftwareDeveloper()
+ " for run id " + runId + ": "
+ ex.getMessage(), runId);
return;
}
File inputsFile = new File(filename);
// String inputsFileWithRunIdsPath = OUTPUT_DIRECTORY + runId + File.separator + FILE_NAME_FOR_INPUTS_WITH_RUN_IDS;
// String urlForFileWithRunIds = BASE_URL + runId + "/" + FILE_NAME_FOR_INPUTS_WITH_RUN_IDS;
// File inputFileWithRunIds = new File(inputsFileWithRunIdsPath);
// inputFileWithRunIds.getParentFile().mkdirs();
StringBuilder stBuild = new StringBuilder();
Scanner sc = new Scanner(inputsFile);
try {
int lineCounter = 1;
while (sc.hasNextLine()) {
String line = sc.nextLine();
String[] params = line.split(",");
BatchConfigRecord batchConfigRecord = new BatchConfigRecord(
params);
if (message instanceof RunSimulationsMessage) {
RunSimulationMessage currentRunSimulationMessage = populateTemplateWithRecord(
message, batchConfigRecord);
RunMethod runMethod = new RunMethodForSimulationAndVisualization(
authentication,
message.getSimulatorIdentification(),
currentRunSimulationMessage);
RunResultAndSimulationGroupId runResultandSimulationGroupId = runMethod.stageInDatabase(simulationGroupId);
RunResult runResult = runResultandSimulationGroupId.getRunResult();
String lineWithRunId = line + "," + runResult.getRunId();
stBuild.append(lineWithRunId).append("\n");
// boolean translatorRunSuccessful = TranslatorServiceAccessor
// .runTranslatorAndReturnIfRunWasSuccessful(
// runId, dbUtils);
// if (!translatorRunSuccessful) {
// return;
if (!isNonErrorCachedStatus(runResult.getMethodCallStatus().getStatus())) {
ApolloServiceErrorHandler
.writeErrorToErrorFile(
"Error staging job using line "
+ String.valueOf(lineCounter)
+ " of the batch configuration file. "
+ "Broker returned the following status: "
+ runResult
+ simulatorIdentification
.getSoftwareVersion()
+ ", developer: "
+ simulatorIdentification
.getSoftwareDeveloper()
+ " run id " + runId + ".",
runId);
return;
}
}
lineCounter++;
}
boolean translatorRunSuccessful = TranslatorServiceAccessor
.runTranslatorAndReturnIfRunWasSuccessful(
runId, dbUtils);
if (!translatorRunSuccessful) {
return;
}
} finally {
sc.close();
}
try {
// add the text data content for the URL
int dataContentKey = dbUtils.addTextDataContent(stBuild.toString());
int runDataDescriptionId = dbUtils.getRunDataDescriptionId(ApolloDbUtils.DbContentDataFormatEnum.TEXT, FILE_NAME_FOR_INPUTS_WITH_RUN_IDS,
ApolloDbUtils.DbContentDataType.CONFIGURATION_FILE, BROKER_SERVICE_SOFTWARE_ID_KEY, ApolloServiceConstants.END_USER_APPLICATION_SOURCE_ID);
dbUtils.associateContentWithRunId(runId, dataContentKey, runDataDescriptionId);
} catch (ApolloDatabaseException ex) {
ApolloServiceErrorHandler.writeErrorToErrorFile(
"ApolloDatabaseException inserting text data content for run: " + ex.getMessage(), runId);
} catch (ClassNotFoundException ex) {
ApolloServiceErrorHandler.writeErrorToErrorFile(
"ClassNotFoundException inserting text data content for run: " + ex.getMessage(), runId);
} catch (SQLException ex) {
ApolloServiceErrorHandler.writeErrorToErrorFile(
"SQLException inserting text data content for run: " + ex.getMessage(), runId);
}
} catch (IOException e) {
logger.error("Error writing error file!: " + e.getMessage());
}
}
public RunSimulationsThread(Authentication authentication,
RunSimulationsMessage message, BigInteger runId,
BigInteger simulationGroupId) {
super(runId);
this.message = message;
this.simulationGroupId = simulationGroupId;
this.authentication = authentication;
try {
this.configFileUrl = new URL(message.getBatchConfigurationFile());
} catch (MalformedURLException e) {
error = e;
}
}
private void startSimulations() {
SoftwareIdentification simulatorIdentification = message.getSimulatorIdentification();
String url = null;
try {
try {
url = dbUtils.getUrlForSoftwareIdentification(simulatorIdentification);
SimulatorServiceEI simulatorPort;
try {
simulatorPort = new SimulatorServiceV300(new URL(url)).getSimulatorServiceEndpoint();
} catch (Exception e) {
ApolloServiceErrorHandler.writeErrorToErrorFile(
"Unable to get simulator port for url: " + url + "\n\tError was: " + e.getMessage(),
runId);
return;
}
// disable chunking for ZSI
Client simulatorClient = ClientProxy.getClient(simulatorPort);
HTTPConduit simulatorHttp = (HTTPConduit) simulatorClient.getConduit();
HTTPClientPolicy simulatorHttpClientPolicy = new HTTPClientPolicy();
simulatorHttpClientPolicy.setConnectionTimeout(36000);
simulatorHttpClientPolicy.setAllowChunking(false);
simulatorHttp.setClient(simulatorHttpClientPolicy);
try {
simulatorPort.runSimulations(runId);
} catch (WebServiceException e) {
ApolloServiceErrorHandler.writeErrorToErrorFile("Error calling runSimulation(): " + "\n\tError was: " + e.getMessage(),
runId);
return;
}
} catch (ApolloDatabaseKeyNotFoundException ex) {
ApolloServiceErrorHandler.writeErrorToErrorFile(
"Apollo database key not found attempting to get URL for simulator: "
+ simulatorIdentification.getSoftwareName() + ", version: "
+ simulatorIdentification.getSoftwareVersion() + ", developer: "
+ simulatorIdentification.getSoftwareDeveloper() + " for run id " + runId + ": "
+ ex.getMessage(), runId);
return;
} catch (ClassNotFoundException ex) {
ApolloServiceErrorHandler.writeErrorToErrorFile(
"ClassNotFoundException attempting to get URL for simulator: "
+ simulatorIdentification.getSoftwareName() + ", version: "
+ simulatorIdentification.getSoftwareVersion() + ", developer: "
+ simulatorIdentification.getSoftwareDeveloper() + " for run id " + runId + ": "
+ ex.getMessage(), runId);
return;
} catch (MalformedURLException ex) {
ApolloServiceErrorHandler.writeErrorToErrorFile(
"MalformedURLException attempting to create port for simulator: "
+ simulatorIdentification.getSoftwareName() + ", version: "
+ simulatorIdentification.getSoftwareVersion() + ", developer: "
+ simulatorIdentification.getSoftwareDeveloper() + " for run id " + runId + ". URL was: " + url
+ ". Error message was: " + ex.getMessage(), runId);
return;
} catch (SQLException ex) {
ApolloServiceErrorHandler.writeErrorToErrorFile(
"SQLException attempting to get URL for simulator: " + simulatorIdentification.getSoftwareName()
+ ", version: " + simulatorIdentification.getSoftwareVersion() + ", developer: "
+ simulatorIdentification.getSoftwareDeveloper() + " for run id " + runId + ": "
+ ex.getMessage(), runId);
return;
}
try {
dbUtils.updateLastServiceToBeCalledForRun(runId, simulatorIdentification);
} catch (ApolloDatabaseKeyNotFoundException ex) {
ApolloServiceErrorHandler.writeErrorToErrorFile("Apollo database key not found attempting to update last service"
+ " call for run id " + runId + ": " + ex.getMessage(), runId);
} catch (SQLException ex) {
ApolloServiceErrorHandler.writeErrorToErrorFile("SQLException attempting to update last service" + " call for run id " + runId
+ ": " + ex.getMessage(), runId);
} catch (ClassNotFoundException ex) {
ApolloServiceErrorHandler.writeErrorToErrorFile("ClassNotFoundException attempting to update last service" + " call for run id "
+ runId + ": " + ex.getMessage(), runId);
} catch (ApolloDatabaseException ex) {
ApolloServiceErrorHandler.writeErrorToErrorFile("ApolloDatabaseException attempting to update last service" + " call for run id "
+ runId + ": " + ex.getMessage(), runId);
}
} catch (IOException ex) {
logger.error("Error writing error file!: " + ex.getMessage());
}
}
@Override
public void run() {
if (error != null) {
SoftwareIdentification simulatorIdentification = message
.getSimulatorIdentification();
try {
ApolloServiceErrorHandler.writeErrorToErrorFile(
"Error staging batch run for: "
+ simulatorIdentification.getSoftwareName()
+ ", version: "
+ simulatorIdentification.getSoftwareVersion()
+ ", developer: "
+ simulatorIdentification
.getSoftwareDeveloper()
+ " for run id " + runId + ": "
+ error.getMessage(), runId);
} catch (IOException e) {
logger.error("Error writing error file!: " + e.getMessage());
}
return;
}
queueAndTranslateRuns();
startSimulations();
}
@Override
public void setAuthenticationPasswordFieldToBlank() {
message.getAuthentication().setRequesterPassword("");
}
static {
brokerServiceSoftwareId = new SoftwareIdentification();
brokerServiceSoftwareId.setSoftwareDeveloper("UPitt");
brokerServiceSoftwareId.setSoftwareName("Broker Service");
brokerServiceSoftwareId.setSoftwareType(ApolloSoftwareTypeEnum.BROKER);
brokerServiceSoftwareId.setSoftwareVersion("3.0.0");
try {
BROKER_SERVICE_SOFTWARE_ID_KEY = dbUtils.getSoftwareIdentificationKey(brokerServiceSoftwareId);
} catch (ApolloDatabaseException ex) {
throw new ExceptionInInitializerError("ApolloDatabaseException getting broker service software key: " + ex.getMessage());
}
}
}
|
package org.eclipse.smarthome.core.thing;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import org.eclipse.jdt.annotation.Nullable;
import org.eclipse.smarthome.core.thing.i18n.ChannelTypeI18nLocalizationService;
import org.eclipse.smarthome.core.thing.type.ChannelType;
import org.eclipse.smarthome.core.thing.type.ChannelTypeBuilder;
import org.eclipse.smarthome.core.thing.type.ChannelTypeProvider;
import org.eclipse.smarthome.core.thing.type.ChannelTypeUID;
import org.eclipse.smarthome.core.types.EventDescription;
import org.eclipse.smarthome.core.types.EventOption;
import org.eclipse.smarthome.core.types.StateDescription;
import org.eclipse.smarthome.core.types.StateDescriptionFragmentBuilder;
import org.eclipse.smarthome.core.types.StateOption;
import org.eclipse.smarthome.core.util.BundleResolver;
import org.osgi.framework.Bundle;
import org.osgi.service.component.annotations.Component;
import org.osgi.service.component.annotations.Reference;
/**
* Implementation providing default system wide channel types
*
* @author Ivan Iliev - Initial Contribution
* @author Chris Jackson - Added battery level
* @author Dennis Nobel - Changed to {@link ChannelTypeProvider}
* @author Markus Rathgeb - Make battery-low indication read-only
* @author Moritz Kammerer - Added system trigger types
* @author Christoph Weitkamp - Added support for translation
* @author Stefan Triller - Added more system channels
* @author Christoph Weitkamp - factored out common i18n aspects into ThingTypeI18nLocalizationService
*/
@Component
public class DefaultSystemChannelTypeProvider implements ChannelTypeProvider {
static final String BINDING_ID = "system";
/**
* Signal strength default system wide {@link ChannelType}. Represents signal strength of a device as a number
* with values 0, 1, 2, 3 or 4, 0 being worst strength and 4 being best strength.
*/
public static final ChannelType SYSTEM_CHANNEL_SIGNAL_STRENGTH = ChannelTypeBuilder
.state(new ChannelTypeUID(BINDING_ID, "signal-strength"), "Signal Strength", "Number")
.withCategory("QualityOfService")
.withStateDescription(new StateDescription(BigDecimal.ZERO, new BigDecimal(4), BigDecimal.ONE, null, true,
Arrays.asList(new StateOption("0", "no signal"), new StateOption("1", "weak"),
new StateOption("2", "average"), new StateOption("3", "good"),
new StateOption("4", "excellent"))))
.build();
/**
* Low battery default system wide {@link ChannelType}. Represents a low battery warning with possible values
* on/off.
*/
public static final ChannelType SYSTEM_CHANNEL_LOW_BATTERY = ChannelTypeBuilder
.state(new ChannelTypeUID(BINDING_ID, "low-battery"), "Low Battery", "Switch").withCategory("Battery")
.withStateDescription(
StateDescriptionFragmentBuilder.create().withReadOnly(true).build().toStateDescription())
.build();
/**
* Battery level default system wide {@link ChannelType}. Represents the battery level as a percentage.
*/
public static final ChannelType SYSTEM_CHANNEL_BATTERY_LEVEL = ChannelTypeBuilder
.state(new ChannelTypeUID(BINDING_ID, "battery-level"), "Battery Level", "Number").withCategory("Battery")
.withStateDescription(
new StateDescription(BigDecimal.ZERO, new BigDecimal(100), BigDecimal.ONE, "%.0f %%", true, null))
.build();
/**
* System wide trigger {@link ChannelType} without event options.
*/
public static final ChannelType SYSTEM_TRIGGER = ChannelTypeBuilder
.trigger(new ChannelTypeUID(BINDING_ID, "trigger"), "Trigger").build();
/**
* System wide trigger {@link ChannelType} which triggers "PRESSED" and "RELEASED" events.
*/
public static final ChannelType SYSTEM_RAWBUTTON = ChannelTypeBuilder
.trigger(new ChannelTypeUID(BINDING_ID, "rawbutton"), "Raw button")
.withEventDescription(new EventDescription(Arrays.asList(new EventOption(CommonTriggerEvents.PRESSED, null),
new EventOption(CommonTriggerEvents.RELEASED, null))))
.build();
/**
* System wide trigger {@link ChannelType} which triggers "SHORT_PRESSED", "DOUBLE_PRESSED" and "LONG_PRESSED"
* events.
*/
public static final ChannelType SYSTEM_BUTTON = ChannelTypeBuilder
.trigger(new ChannelTypeUID(BINDING_ID, "button"), "Button")
.withEventDescription(
new EventDescription(Arrays.asList(new EventOption(CommonTriggerEvents.SHORT_PRESSED, null),
new EventOption(CommonTriggerEvents.DOUBLE_PRESSED, null),
new EventOption(CommonTriggerEvents.LONG_PRESSED, null))))
.build();
/**
* System wide trigger {@link ChannelType} which triggers "DIR1_PRESSED", "DIR1_RELEASED", "DIR2_PRESSED" and
* "DIR2_RELEASED" events.
*/
public static final ChannelType SYSTEM_RAWROCKER = ChannelTypeBuilder
.trigger(new ChannelTypeUID(BINDING_ID, "rawrocker"), "Raw rocker button")
.withEventDescription(
new EventDescription(Arrays.asList(new EventOption(CommonTriggerEvents.DIR1_PRESSED, null),
new EventOption(CommonTriggerEvents.DIR1_RELEASED, null),
new EventOption(CommonTriggerEvents.DIR2_PRESSED, null),
new EventOption(CommonTriggerEvents.DIR2_RELEASED, null))))
.build();
/**
* Power: default system wide {@link ChannelType} which allows turning off (potentially on) a device
*/
public static final ChannelType SYSTEM_POWER = ChannelTypeBuilder
.state(new ChannelTypeUID(BINDING_ID, "power"), "Power", "Switch")
.withDescription("Device is operable when channel has state ON").build();
/**
* Location: default system wide {@link ChannelType} which displays a location
*/
public static final ChannelType SYSTEM_LOCATION = ChannelTypeBuilder
.state(new ChannelTypeUID(BINDING_ID, "location"), "Location", "Location")
.withDescription("Location in lat./lon./height coordinates")
.withStateDescription(StateDescriptionFragmentBuilder.create().withReadOnly(true)
.withPattern("%2$s°N %3$s°E %1$sm").build().toStateDescription())
.build();
/**
* Motion: default system wide {@link ChannelType} which indications whether motion was detected (state ON)
*/
public static final ChannelType SYSTEM_MOTION = ChannelTypeBuilder
.state(new ChannelTypeUID(BINDING_ID, "motion"), "Motion", "Switch")
.withDescription("Motion detected by the device").withCategory("Motion").withStateDescription(
StateDescriptionFragmentBuilder.create().withReadOnly(true).build().toStateDescription())
.build();
/**
* Brightness: default system wide {@link ChannelType} which allows changing the brightness from 0-100%
*/
public static final ChannelType SYSTEM_BRIGHTNESS = ChannelTypeBuilder
.state(new ChannelTypeUID(BINDING_ID, "brightness"), "Brightness", "Dimmer")
.withDescription("Controls the brightness and switches the light on and off").withCategory("DimmableLight")
.withStateDescription(
new StateDescription(BigDecimal.ZERO, new BigDecimal(100), null, "%d %%", false, null))
.build();
/**
* Color: default system wide {@link ChannelType} which allows changing the color
*/
public static final ChannelType SYSTEM_COLOR = ChannelTypeBuilder
.state(new ChannelTypeUID(BINDING_ID, "color"), "Color", "Color")
.withDescription("Controls the color of the light").withCategory("ColorLight").build();
/**
* Color-temperature: default system wide {@link ChannelType} which allows changing the color temperature
*/
public static final ChannelType SYSTEM_COLOR_TEMPERATURE = ChannelTypeBuilder
.state(new ChannelTypeUID(BINDING_ID, "color-temperature"), "Color Temperature", "Dimmer")
.withDescription("Controls the color temperature of the light").withCategory("ColorLight")
.withStateDescription(new StateDescription(BigDecimal.ZERO, new BigDecimal(100), null, "%d", false, null))
.build();
// media channels
/**
* Volume: default system wide {@link ChannelType} which allows changing the audio volume from 0-100%
*/
public static final ChannelType SYSTEM_VOLUME = ChannelTypeBuilder
.state(new ChannelTypeUID(BINDING_ID, "volume"), "Volume", "Dimmer")
.withDescription("Change the sound volume of a device")
.withStateDescription(
new StateDescription(BigDecimal.ZERO, new BigDecimal(100), null, "%d %%", false, null))
.withCategory("SoundVolume").build();
/**
* Mute: default system wide {@link ChannelType} which allows muting and un-muting audio
*/
public static final ChannelType SYSTEM_MUTE = ChannelTypeBuilder
.state(new ChannelTypeUID(BINDING_ID, "mute"), "Mute", "Switch").withDescription("Mute audio of the device")
.withCategory("SoundVolume").build();
/**
* Media-control: system wide {@link ChannelType} which controls a media player
*/
public static final ChannelType SYSTEM_MEDIA_CONTROL = ChannelTypeBuilder
.state(new ChannelTypeUID(BINDING_ID, "media-control"), "Media Control", "Player")
.withCategory("MediaControl").build();
/**
* Media-title: default system wide {@link ChannelType} which displays the title of a (played) song
*/
public static final ChannelType SYSTEM_MEDIA_TITLE = ChannelTypeBuilder
.state(new ChannelTypeUID(BINDING_ID, "media-title"), "Media Title", "String")
.withDescription("Title of a (played) media file").withStateDescription(
StateDescriptionFragmentBuilder.create().withReadOnly(true).build().toStateDescription())
.build();
/**
* Media-artist: default system wide {@link ChannelType} which displays the artist of a (played) song
*/
public static final ChannelType SYSTEM_MEDIA_ARTIST = ChannelTypeBuilder
.state(new ChannelTypeUID(BINDING_ID, "media-artist"), "Media Artist", "String")
.withDescription("Artist of a (played) media file").withStateDescription(
StateDescriptionFragmentBuilder.create().withReadOnly(true).build().toStateDescription())
.build();
// weather channels
/**
* Wind-direction: system wide {@link ChannelType} which shows the wind direction in degrees 0-360
*/
public static final ChannelType SYSTEM_WIND_DIRECTION = ChannelTypeBuilder
.state(new ChannelTypeUID(BINDING_ID, "wind-direction"), "Wind Direction", "Number:Angle")
.withDescription("Current wind direction expressed as an angle").withCategory("Wind")
.withStateDescription(
new StateDescription(BigDecimal.ZERO, new BigDecimal(360), null, "%.0f %unit%", true, null))
.build();
/**
* Wind-speed: system wide {@link ChannelType} which shows the wind speed
*/
public static final ChannelType SYSTEM_WIND_SPEED = ChannelTypeBuilder
.state(new ChannelTypeUID(BINDING_ID, "wind-speed"), "Wind Speed", "Number:Speed")
.withDescription("Current wind speed").withCategory("Wind")
.withStateDescription(StateDescriptionFragmentBuilder.create().withReadOnly(true).withPattern("%.1f %unit%")
.build().toStateDescription())
.build();
/**
* Outdoor-temperature: system wide {@link ChannelType} which shows the outdoor temperature
*/
public static final ChannelType SYSTEM_OUTDOOR_TEMPERATURE = ChannelTypeBuilder
.state(new ChannelTypeUID(BINDING_ID, "outdoor-temperature"), "Outdoor Temperature", "Number:Temperature")
.withDescription("Current outdoor temperature").withCategory("Temperature")
.withStateDescription(StateDescriptionFragmentBuilder.create().withReadOnly(true).withPattern("%.1f %unit%")
.build().toStateDescription())
.build();
/**
* Atmospheric-humidity: system wide {@link ChannelType} which shows the atmospheric humidity
*/
public static final ChannelType SYSTEM_ATMOSPHERIC_HUMIDITY = ChannelTypeBuilder
.state(new ChannelTypeUID(BINDING_ID, "atmospheric-humidity"), "Atmospheric Humidity",
"Number:Dimensionless")
.withDescription("Current atmospheric relative humidity").withCategory("Humidity")
.withStateDescription(StateDescriptionFragmentBuilder.create().withReadOnly(true).withPattern("%.0f %%")
.build().toStateDescription())
.build();
/**
* Barometric-pressure: system wide {@link ChannelType} which shows the barometric pressure
*/
public static final ChannelType SYSTEM_BAROMETRIC_PRESSURE = ChannelTypeBuilder
.state(new ChannelTypeUID(BINDING_ID, "barometric-pressure"), "Barometric Pressure", "Number:Pressure")
.withDescription("Current barometric pressure").withCategory("Pressure")
.withStateDescription(StateDescriptionFragmentBuilder.create().withReadOnly(true).withPattern("%.3f %unit%")
.build().toStateDescription())
.build();
private static class LocalizedChannelTypeKey {
public final String locale;
public final UID uid;
public LocalizedChannelTypeKey(UID uid, String locale) {
this.uid = uid;
this.locale = locale;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
LocalizedChannelTypeKey other = (LocalizedChannelTypeKey) obj;
if (locale == null) {
if (other.locale != null) {
return false;
}
} else if (!locale.equals(other.locale)) {
return false;
}
if (uid == null) {
if (other.uid != null) {
return false;
}
} else if (!uid.equals(other.uid)) {
return false;
}
return true;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((locale == null) ? 0 : locale.hashCode());
result = prime * result + ((uid == null) ? 0 : uid.hashCode());
return result;
}
}
private static final Collection<ChannelType> CHANNEL_TYPES = Collections
.unmodifiableList(Stream.of(SYSTEM_CHANNEL_SIGNAL_STRENGTH, SYSTEM_CHANNEL_LOW_BATTERY,
SYSTEM_CHANNEL_BATTERY_LEVEL, SYSTEM_TRIGGER, SYSTEM_RAWBUTTON, SYSTEM_BUTTON, SYSTEM_RAWROCKER,
SYSTEM_POWER, SYSTEM_LOCATION, SYSTEM_MOTION, SYSTEM_BRIGHTNESS, SYSTEM_COLOR,
SYSTEM_COLOR_TEMPERATURE, SYSTEM_VOLUME, SYSTEM_MUTE, SYSTEM_MEDIA_CONTROL, SYSTEM_MEDIA_TITLE,
SYSTEM_MEDIA_ARTIST, SYSTEM_WIND_DIRECTION, SYSTEM_WIND_SPEED, SYSTEM_OUTDOOR_TEMPERATURE,
SYSTEM_ATMOSPHERIC_HUMIDITY, SYSTEM_BAROMETRIC_PRESSURE).collect(Collectors.toList()));
private final Map<LocalizedChannelTypeKey, ChannelType> localizedChannelTypeCache = new ConcurrentHashMap<>();
private ChannelTypeI18nLocalizationService channelTypeI18nLocalizationService;
private BundleResolver bundleResolver;
@Override
public Collection<ChannelType> getChannelTypes(Locale locale) {
final List<ChannelType> allChannelTypes = new ArrayList<>();
final Bundle bundle = bundleResolver.resolveBundle(DefaultSystemChannelTypeProvider.class);
for (final ChannelType channelType : CHANNEL_TYPES) {
allChannelTypes.add(createLocalizedChannelType(bundle, channelType, locale));
}
return allChannelTypes;
}
@Override
public ChannelType getChannelType(ChannelTypeUID channelTypeUID, Locale locale) {
final Bundle bundle = bundleResolver.resolveBundle(DefaultSystemChannelTypeProvider.class);
for (final ChannelType channelType : CHANNEL_TYPES) {
if (channelTypeUID.equals(channelType.getUID())) {
return createLocalizedChannelType(bundle, channelType, locale);
}
}
return null;
}
@Reference
public void setChannelTypeI18nLocalizationService(
final ChannelTypeI18nLocalizationService channelTypeI18nLocalizationService) {
this.channelTypeI18nLocalizationService = channelTypeI18nLocalizationService;
}
public void unsetChannelTypeI18nLocalizationService(
final ChannelTypeI18nLocalizationService channelTypeI18nLocalizationService) {
this.channelTypeI18nLocalizationService = null;
}
@Reference
public void setBundleResolver(BundleResolver bundleResolver) {
this.bundleResolver = bundleResolver;
}
public void unsetBundleResolver(BundleResolver bundleResolver) {
this.bundleResolver = bundleResolver;
}
private ChannelType createLocalizedChannelType(Bundle bundle, ChannelType channelType, Locale locale) {
LocalizedChannelTypeKey localizedChannelTypeKey = getLocalizedChannelTypeKey(channelType.getUID(), locale);
ChannelType cachedEntry = localizedChannelTypeCache.get(localizedChannelTypeKey);
if (cachedEntry != null) {
return cachedEntry;
}
ChannelType localizedChannelType = localize(bundle, channelType, locale);
if (localizedChannelType != null) {
localizedChannelTypeCache.put(localizedChannelTypeKey, localizedChannelType);
return localizedChannelType;
} else {
return channelType;
}
}
private @Nullable ChannelType localize(Bundle bundle, ChannelType channelType, Locale locale) {
if (channelTypeI18nLocalizationService == null) {
return null;
}
return channelTypeI18nLocalizationService.createLocalizedChannelType(bundle, channelType, locale);
}
private LocalizedChannelTypeKey getLocalizedChannelTypeKey(UID uid, Locale locale) {
return new LocalizedChannelTypeKey(uid, locale != null ? locale.toLanguageTag() : null);
}
}
|
package de.lmu.ifi.dbs.database;
import de.lmu.ifi.dbs.data.ClassLabel;
import de.lmu.ifi.dbs.math.linearalgebra.Matrix;
import de.lmu.ifi.dbs.varianceanalysis.LocalPCA;
import de.lmu.ifi.dbs.utilities.ConstantObject;
import java.util.BitSet;
import java.util.List;
/**
* An AssociationID is used by databases as a unique identifier for specific
* associations to single objects. Such as label, local similarity measure.
* There is no association possible without a specific AssociationID defined
* within this class. <p/> An AssociationID provides also information concerning
* the class of the associated objects.
*
* @author Arthur Zimek (<a
* href="mailto:zimek@dbs.ifi.lmu.de">zimek@dbs.ifi.lmu.de</a>)
*/
public class AssociationID extends ConstantObject {
/**
* The standard association id to associate a label to an object.
*/
public static final AssociationID LABEL = new AssociationID("label", String.class);
/**
* The association id to associate a class to an object.
*/
public static final AssociationID CLASS = new AssociationID("class", ClassLabel.class);
/**
* The association id to associate an external id to an object.
*/
public static final AssociationID EXTERNAL_ID = new AssociationID("externalID", String.class);
/**
* The association id to associate a correlation pca to an object.
*/
public static final AssociationID LOCAL_PCA = new AssociationID("pca", LocalPCA.class);
/**
* The association id to associate a local dimensionality (e.g. the correlation dimensionality)
* to an object.
*/
public static final AssociationID LOCAL_DIMENSIONALITY = new AssociationID("localDimensionality", Integer.class);
/**
* The association id to associate the neighbors of an object.
*/
public static final AssociationID NEIGHBORS = new AssociationID("neighbors", List.class);
/**
* The association id to associate the LRD of an object for the LOF
* algorithm.
*/
public static final AssociationID LRD = new AssociationID("lrd", Double.class);
/**
* The association id to associate the locally weighted matrix of an object
* for the locally weighted distance function.
*/
public static final AssociationID LOCALLY_WEIGHTED_MATRIX = new AssociationID("locallyWeightedMatrix", Matrix.class);
/**
* The association id to associate a preference vector.
*/
public static final AssociationID PREFERENCE_VECTOR = new AssociationID("preferenceVector", BitSet.class);
/**
* The serial version UID.
*/
private static final long serialVersionUID = 8115554038339292192L;
/**
* The Class type related to this AssociationID.
*/
private Class type;
/**
* Provides a new AssociationID of the given name and type. <p/> All
* AssociationIDs are unique w.r.t. their name. An AssociationID provides
* information of which class the associated objects are.
*
* @param name name of the association
* @param type class of the objects that are associated under this
* AssociationID
*/
private AssociationID(final String name, final Class type) {
super(name);
try {
this.type = Class.forName(type.getName());
}
catch (ClassNotFoundException e) {
throw new IllegalArgumentException("Invalid class name \""
+ type.getName() + "\" for property \"" + name + "\".");
}
}
/**
* Returns the type of the AssociationID.
*
* @return the type of the AssociationID
*/
public Class getType() {
try {
return Class.forName(type.getName());
}
catch (ClassNotFoundException e) {
throw new IllegalStateException("Invalid class name \""
+ type.getName() + "\" for property \"" + this.getName()
+ "\".");
}
}
/**
* Returns the AssociationID for the given name if it exists, null
* otherwise.
*
* @param name the name of the desired AssociationID
* @return the AssociationID for the given name if it exists, null otherwise
*/
public AssociationID getAssociationID(final String name) {
return (AssociationID) AssociationID.lookup(AssociationID.class, name);
}
}
|
package io.subutai.core.identity.impl;
import java.io.IOException;
import java.security.AccessControlContext;
import java.security.AccessControlException;
import java.security.AccessController;
import java.security.PrivilegedAction;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Random;
import java.util.UUID;
import java.util.concurrent.Callable;
import javax.annotation.security.PermitAll;
import javax.annotation.security.RolesAllowed;
import javax.security.auth.Subject;
import javax.security.auth.callback.Callback;
import javax.security.auth.callback.CallbackHandler;
import javax.security.auth.callback.NameCallback;
import javax.security.auth.callback.PasswordCallback;
import javax.security.auth.callback.UnsupportedCallbackException;
import javax.security.auth.login.LoginContext;
import org.bouncycastle.openpgp.PGPException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.apache.commons.lang.time.DateUtils;
import com.google.common.base.Strings;
import io.subutai.common.dao.DaoManager;
import io.subutai.common.security.crypto.pgp.KeyPair;
import io.subutai.common.security.crypto.pgp.PGPEncryptionUtil;
import io.subutai.common.security.objects.PermissionObject;
import io.subutai.common.security.objects.PermissionOperation;
import io.subutai.common.security.objects.PermissionScope;
import io.subutai.common.security.objects.SecurityKeyType;
import io.subutai.common.security.objects.TokenType;
import io.subutai.common.security.objects.UserStatus;
import io.subutai.common.security.objects.UserType;
import io.subutai.common.security.token.TokenUtil;
import io.subutai.core.identity.api.IdentityManager;
import io.subutai.core.identity.api.SessionManager;
import io.subutai.core.identity.api.dao.IdentityDataService;
import io.subutai.core.identity.api.model.Permission;
import io.subutai.core.identity.api.model.Role;
import io.subutai.core.identity.api.model.Session;
import io.subutai.core.identity.api.model.User;
import io.subutai.core.identity.api.model.UserToken;
import io.subutai.core.identity.impl.dao.IdentityDataServiceImpl;
import io.subutai.core.identity.impl.model.PermissionEntity;
import io.subutai.core.identity.impl.model.RoleEntity;
import io.subutai.core.identity.impl.model.SessionEntity;
import io.subutai.core.identity.impl.model.UserEntity;
import io.subutai.core.identity.impl.model.UserTokenEntity;
import io.subutai.core.security.api.SecurityManager;
@PermitAll
public class IdentityManagerImpl implements IdentityManager
{
private static final Logger LOGGER = LoggerFactory.getLogger( IdentityManagerImpl.class.getName() );
private IdentityDataService identityDataService = null;
private DaoManager daoManager = null;
private SecurityManager securityManager = null;
private SessionManager sessionManager = null;
public IdentityManagerImpl()
{
}
private CallbackHandler getCalbackHandler( final String userName, final String password )
{
CallbackHandler callbackHandler = new CallbackHandler()
{
public void handle( Callback[] callbacks ) throws IOException, UnsupportedCallbackException
{
for ( Callback callback : callbacks )
{
if ( callback instanceof NameCallback )
{
( ( NameCallback ) callback ).setName( userName );
}
else if ( callback instanceof PasswordCallback )
{
( ( PasswordCallback ) callback ).setPassword( password.toCharArray() );
}
else
{
throw new UnsupportedCallbackException( callback );
}
}
}
};
return callbackHandler;
}
@PermitAll
@Override
public Session login( String userName, String password )
{
try
{
Session userSession = null;
CallbackHandler ch = getCalbackHandler( userName, password );
Subject subject = new Subject();
LoginContext loginContext = new LoginContext( "karaf", subject, ch );
loginContext.login();
while ( subject.getPrivateCredentials().iterator().hasNext() )
{
Object obj = subject.getPrivateCredentials().iterator().next();
if ( obj instanceof SessionEntity )
{
userSession = ( Session ) obj;
userSession.setSubject( subject );
break;
}
}
return userSession;
}
catch ( Exception ex )
{
return null;
}
}
@PermitAll
@Override
public SessionManager getSessionManager()
{
return sessionManager;
}
@PermitAll
@Override
public Session authenticateSession( String login, String password )
{
String sessionId;
Session session = null;
User user = null;
if ( login.equals( "token" ) )
{
sessionId = password;
}
else
{
sessionId = UUID.randomUUID() + "-" + System.currentTimeMillis();
}
session = sessionManager.getValidSession( sessionId );
if ( session == null )
{
user = authenticateUser( login, password );
if ( user == null )
{
return null;
}
}
session = sessionManager.startSession( sessionId, session, user );
return session;
}
@RolesAllowed( "Identity-Management|Write" )
@Override
public UserToken createUserToken( User user, String token, String secret, String issuer, int tokenType,
Date validDate )
{
try
{
UserToken userToken = new UserTokenEntity();
if ( Strings.isNullOrEmpty( token ) )
{
token = UUID.randomUUID().toString();
}
if ( Strings.isNullOrEmpty( issuer ) )
{
issuer = "io.subutai";
}
if ( Strings.isNullOrEmpty( secret ) )
{
secret = UUID.randomUUID().toString();
}
if ( validDate == null )
{
validDate = DateUtils
.addMinutes( new Date( System.currentTimeMillis() ), sessionManager.getSessionTimeout() );
}
userToken.setToken( token );
userToken.setHashAlgorithm( "HS256" );
userToken.setIssuer( issuer );
userToken.setSecret( secret );
userToken.setUserId( user.getId() );
userToken.setType( tokenType );
userToken.setValidDate( validDate );
identityDataService.persistUserToken( userToken );
return userToken;
}
catch ( Exception ex )
{
return null;
}
}
@PermitAll
@Override
public void logout()
{
try
{
//loginContext.logout();
}
catch ( Exception e )
{
}
}
@PermitAll
@Override
public String getUserToken( String userName, String password )
{
String token = "";
User user = authenticateUser( userName, password );
if ( user != null )
{
UserToken uToken = identityDataService.getUserToken( user.getId() );
if ( uToken == null )
{
uToken = createUserToken( user, "", "", "", TokenType.Session.getId(), null );
}
token = uToken.getFullToken();
}
return token;
}
@PermitAll
@Override
public User authenticateByToken( String token )
{
String subject = TokenUtil.getSubject( token );
UserToken userToken = identityDataService.getValidUserToken( subject );
if ( userToken != null )
{
if ( !TokenUtil.verifySignature( token, userToken.getSecret() ) )
{
return null;
}
else
{
return getUser( userToken.getUserId() );
}
}
else
{
return null;
}
}
@PermitAll
@Override
public User authenticateUser( String userName, String password )
{
User user = null;
if ( userName.equalsIgnoreCase( "token" ) )
{
user = authenticateByToken( password );
}
else
{
user = identityDataService.getUserByUsername( userName );
if ( user != null && user.isApproved() )
{
if ( !user.getPassword().equals( password ) || user.getStatus() == UserStatus.Disabled.getId() )
{
return null;
}
}
else
{
return null;
}
}
return user;
}
@PermitAll
@Override
public List<User> getAllUsers()
{
List<User> result = new ArrayList<>();
result.addAll( identityDataService.getAllUsers() );
return result;
}
@RolesAllowed( "Identity-Management|Read" )
@Override
public List<User> getAllSystemUsers()
{
List<User> result = new ArrayList<>();
result.addAll( identityDataService.getAllSystemUsers() );
return result;
}
@RolesAllowed( "Identity-Management|Write" )
@Override
public void assignUserRole( long userId, Role role )
{
identityDataService.assignUserRole( userId, role );
}
@PermitAll
@Override
public User getUser( long userId )
{
return identityDataService.getUser( userId );
}
@PermitAll
@Override
public User getActiveUser()
{
Session session = getActiveSession();
if ( session != null )
{
return session.getUser();
}
else
{
return null;
}
}
@PermitAll
@Override
public Session getActiveSession()
{
Session session = null;
try
{
Subject subject = getActiveSubject();
if ( subject != null )
{
while ( subject.getPrivateCredentials().iterator().hasNext() )
{
Object obj = subject.getPrivateCredentials().iterator().next();
if ( obj instanceof SessionEntity )
{
session = ( ( Session ) obj );
break;
}
}
}
}
catch ( Exception ex )
{
LOGGER.error( "*** Error! Cannot find active User. Session is not started" );
}
return session;
}
@PermitAll
@Override
public void runAs( Session userSession, final Callable action )
{
if ( userSession != null )
{
Subject.doAs( userSession.getSubject(), new PrivilegedAction<Void>()
{
@Override
public Void run()
{
try
{
action.call();
}
catch ( Exception ex )
{
LOGGER.error( "**** Error!! Error running privileged action.", ex );
}
return null;
}
} );
}
}
private Subject getActiveSubject()
{
Subject subject = null;
try
{
AccessControlContext acc = AccessController.getContext();
if ( acc == null )
{
throw new RuntimeException( "access control context is null" );
}
subject = Subject.getSubject( acc );
if ( subject == null )
{
throw new RuntimeException( "subject is null" );
}
}
catch ( Exception ex )
{
LOGGER.error( "*** Error! Cannot get auth.subject." );
}
return subject;
}
@RolesAllowed( "Identity-Management|Write" )
@Override
public User createTempUser( String userName, String password, String fullName, String email, int type )
{
@RolesAllowed( "Identity-Management|Write" )
@Override
public User createUser( String userName, String password, String fullName, String email, int type,
final String publicKey, boolean isApproved )
{
User user = new UserEntity();
try
{
@RolesAllowed( "Identity-Management|Delete" )
@Override
public void removeUserRole( long userId, Role role )
{
identityDataService.removeUserRole( userId, role );
}
@PermitAll
@Override
public boolean changeUserPassword( long userId, String oldPassword, String newPassword )
{
User user = identityDataService.getUser( userId );
@RolesAllowed( "Identity-Management|Update" )
@Override
public void updateUser( User user )
{
@RolesAllowed( "Identity-Management|Update" )
@Override
public void updateUser( User user, String publicKey )
{
@RolesAllowed( "Identity-Management|Delete" )
@Override
public void removeUser( long userId )
{
@PermitAll
@Override
public boolean isUserPermitted( User user, PermissionObject permObj, PermissionScope permScope,
PermissionOperation permOp )
{
boolean isPermitted = false;
List<Role> roles = user.getRoles();
for ( Role role : roles )
{
for ( Permission permission : role.getPermissions() )
{
if ( permission.getObject() == permObj.getId() && permission.getScope() == permScope.getId() )
{
switch ( permOp )
{
case Read:
return permission.isRead();
case Write:
return permission.isWrite();
case Update:
return permission.isUpdate();
case Delete:
return permission.isDelete();
}
}
}
}
return isPermitted;
}
@RolesAllowed( "Identity-Management|Write" )
@Override
public Role createRole( String roleName, int roleType )
{
Role role = new RoleEntity();
role.setName( roleName );
role.setType( roleType );
identityDataService.persistRole( role );
return role;
}
@PermitAll
@Override
public List<Role> getAllRoles()
{
return identityDataService.getAllRoles();
}
@PermitAll
@Override
public Role getRole( long roleId )
{
return identityDataService.getRole( roleId );
}
@RolesAllowed( "Identity-Management|Update" )
@Override
public void updateRole( Role role )
{
@RolesAllowed( "Identity-Management|Delete" )
@Override
public void removeRole( long roleId )
{
@RolesAllowed( "Identity-Management|Write" )
@Override
public Permission createPermission( int objectId, int scope, boolean read, boolean write, boolean update,
boolean delete )
{
Permission permission = new PermissionEntity();
permission.setObject( objectId );
permission.setScope( scope );
permission.setRead( read );
permission.setWrite( write );
permission.setUpdate( update );
permission.setDelete( delete );
identityDataService.persistPermission( permission );
return permission;
}
@RolesAllowed( "Identity-Management|Write" )
@Override
public void assignRolePermission( long roleId, Permission permission )
{
identityDataService.assignRolePermission( roleId, permission );
}
@RolesAllowed( "Identity-Management|Write" )
@Override
public void removeAllRolePermissions( long roleId )
{
identityDataService.removeAllRolePermissions( roleId );
}
@RolesAllowed( "Identity-Management|Delete" )
@Override
public void removePermission( long permissionId )
{
identityDataService.removePermission( permissionId );
}
@RolesAllowed( "Identity-Management|Delete" )
@Override
public void removeRolePermission( long roleId, Permission permission )
{
identityDataService.removeRolePermission( roleId, permission );
}
@PermitAll
@Override
public List<Permission> getAllPermissions()
{
return identityDataService.getAllPermissions();
}
@RolesAllowed( "Identity-Management|Update" )
@Override
public void updatePermission( Permission permission )
{
identityDataService.updatePermission( permission );
}
@Override
public IdentityDataService getIdentityDataService()
{
return identityDataService;
}
@PermitAll
@Override
public List<UserToken> getAllUserTokens()
{
return identityDataService.getAllUserTokens();
}
@PermitAll
@Override
public void extendTokenTime( UserToken token, int minutes )
{
token.setValidDate( DateUtils.addMinutes( new Date( System.currentTimeMillis() ), minutes ) );
identityDataService.updateUserToken( token );
}
@PermitAll
@Override
public void updateUserToken( UserToken token )
{
identityDataService.updateUserToken( token );
}
@RolesAllowed( { "Identity-Management|Write", "Identity-Management|Update" } )
@Override
public void updateUserToken( String oldName, User user, String token, String secret, String issuer, int tokenType,
Date validDate )
{
identityDataService.removeUserToken( oldName );
createUserToken( user, token, secret, issuer, tokenType, validDate );
}
@RolesAllowed( { "Identity-Management|Write", "Identity-Management|Delete" } )
@Override
public void removeUserToken( String tokenId )
{
identityDataService.removeUserToken( tokenId );
}
private void removeInvalidTokens()
{
identityDataService.removeInvalidTokens();
}
public DaoManager getDaoManager()
{
return daoManager;
}
public void setDaoManager( DaoManager daoManager )
{
this.daoManager = daoManager;
}
public SecurityManager getSecurityManager()
{
return securityManager;
}
public void setSecurityManager( final SecurityManager securityManager )
{
this.securityManager = securityManager;
}
private boolean validUsername( String username )
{
if ( username.length() == 0 || username.isEmpty() || username.equalsIgnoreCase( "token" ) )
{
return false;
}
User user = identityDataService.getUserByUsername( username );
return user == null;
}
}
|
package org.opendaylight.controller.md.sal.binding.test;
import com.google.common.collect.ImmutableMap;
import com.google.common.util.concurrent.ListeningExecutorService;
import com.google.common.util.concurrent.MoreExecutors;
import java.util.concurrent.Executors;
import javassist.ClassPool;
import org.opendaylight.controller.md.sal.binding.api.DataBroker;
import org.opendaylight.controller.md.sal.binding.api.NotificationPublishService;
import org.opendaylight.controller.md.sal.binding.api.NotificationService;
import org.opendaylight.controller.md.sal.binding.impl.BindingDOMDataBrokerAdapter;
import org.opendaylight.controller.md.sal.binding.impl.BindingDOMNotificationPublishServiceAdapter;
import org.opendaylight.controller.md.sal.binding.impl.BindingDOMNotificationServiceAdapter;
import org.opendaylight.controller.md.sal.binding.impl.BindingToNormalizedNodeCodec;
import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
import org.opendaylight.controller.md.sal.dom.api.DOMDataBroker;
import org.opendaylight.controller.md.sal.dom.broker.impl.DOMNotificationRouter;
import org.opendaylight.controller.md.sal.dom.broker.impl.SerializedDOMDataBroker;
import org.opendaylight.controller.md.sal.dom.store.impl.InMemoryDOMDataStore;
import org.opendaylight.controller.sal.binding.test.util.MockSchemaService;
import org.opendaylight.controller.sal.core.api.model.SchemaService;
import org.opendaylight.controller.sal.core.spi.data.DOMStore;
import org.opendaylight.yangtools.binding.data.codec.gen.impl.DataObjectSerializerGenerator;
import org.opendaylight.yangtools.binding.data.codec.gen.impl.StreamWriterGenerator;
import org.opendaylight.yangtools.binding.data.codec.impl.BindingNormalizedNodeCodecRegistry;
import org.opendaylight.yangtools.sal.binding.generator.impl.GeneratedClassLoadingStrategy;
import org.opendaylight.yangtools.sal.binding.generator.util.JavassistUtils;
import org.opendaylight.yangtools.yang.model.api.SchemaContext;
public class DataBrokerTestCustomizer {
private DOMDataBroker domDataBroker;
private final DOMNotificationRouter domNotificationRouter;
private final MockSchemaService schemaService;
private ImmutableMap<LogicalDatastoreType, DOMStore> datastores;
private final BindingToNormalizedNodeCodec bindingToNormalized;
public ImmutableMap<LogicalDatastoreType, DOMStore> createDatastores() {
return ImmutableMap.<LogicalDatastoreType, DOMStore>builder()
.put(LogicalDatastoreType.OPERATIONAL, createOperationalDatastore())
.put(LogicalDatastoreType.CONFIGURATION,createConfigurationDatastore())
.build();
}
public DataBrokerTestCustomizer() {
schemaService = new MockSchemaService();
final ClassPool pool = ClassPool.getDefault();
final DataObjectSerializerGenerator generator = StreamWriterGenerator.create(JavassistUtils.forClassPool(pool));
final BindingNormalizedNodeCodecRegistry codecRegistry = new BindingNormalizedNodeCodecRegistry(generator);
final GeneratedClassLoadingStrategy loading = GeneratedClassLoadingStrategy.getTCCLClassLoadingStrategy();
bindingToNormalized = new BindingToNormalizedNodeCodec(loading, codecRegistry);
schemaService.registerSchemaContextListener(bindingToNormalized);
domNotificationRouter = DOMNotificationRouter.create(16);
}
public DOMStore createConfigurationDatastore() {
final InMemoryDOMDataStore store = new InMemoryDOMDataStore("CFG", MoreExecutors.newDirectExecutorService());
schemaService.registerSchemaContextListener(store);
return store;
}
public DOMStore createOperationalDatastore() {
final InMemoryDOMDataStore store = new InMemoryDOMDataStore("OPER", MoreExecutors.newDirectExecutorService());
schemaService.registerSchemaContextListener(store);
return store;
}
public DOMDataBroker createDOMDataBroker() {
return new SerializedDOMDataBroker(getDatastores(), getCommitCoordinatorExecutor());
}
public NotificationService createNotificationService() {
return new BindingDOMNotificationServiceAdapter(bindingToNormalized.getCodecRegistry(), domNotificationRouter);
}
public NotificationPublishService createNotificationPublishService() {
return new BindingDOMNotificationPublishServiceAdapter(bindingToNormalized, domNotificationRouter);
}
public ListeningExecutorService getCommitCoordinatorExecutor() {
return MoreExecutors.listeningDecorator(Executors.newSingleThreadExecutor());
}
public DataBroker createDataBroker() {
return new BindingDOMDataBrokerAdapter(getDOMDataBroker(), bindingToNormalized);
}
public BindingToNormalizedNodeCodec getBindingToNormalized() {
return bindingToNormalized;
}
public SchemaService getSchemaService() {
return schemaService;
}
private DOMDataBroker getDOMDataBroker() {
if (domDataBroker == null) {
domDataBroker = createDOMDataBroker();
}
return domDataBroker;
}
private synchronized ImmutableMap<LogicalDatastoreType, DOMStore> getDatastores() {
if (datastores == null) {
datastores = createDatastores();
}
return datastores;
}
public void updateSchema(final SchemaContext ctx) {
schemaService.changeSchema(ctx);
}
public DOMNotificationRouter getDomNotificationRouter() {
return domNotificationRouter;
}
}
|
package org.hibernate.beanvalidation.tck.tests.constraints.containerelement;
import static org.hibernate.beanvalidation.tck.util.ConstraintViolationAssert.assertNoViolations;
import static org.hibernate.beanvalidation.tck.util.ConstraintViolationAssert.assertThat;
import static org.hibernate.beanvalidation.tck.util.ConstraintViolationAssert.pathWith;
import static org.hibernate.beanvalidation.tck.util.ConstraintViolationAssert.violationOf;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.OptionalInt;
import java.util.Set;
import javax.validation.ConstraintViolation;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import javax.validation.valueextraction.Unwrapping;
import org.hibernate.beanvalidation.tck.beanvalidation.Sections;
import org.hibernate.beanvalidation.tck.tests.AbstractTCKTest;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import org.jboss.test.audit.annotations.SpecAssertion;
import org.jboss.test.audit.annotations.SpecVersion;
import org.testng.annotations.Test;
@SpecVersion(spec = "beanvalidation", version = "2.0.0")
public class NestedContainerElementConstraintsTest extends AbstractTCKTest {
@Deployment
public static WebArchive createTestArchive() {
return webArchiveBuilder()
.withTestClass( NestedContainerElementConstraintsTest.class )
.build();
}
@Test
@SpecAssertion(section = Sections.CONSTRAINTDECLARATIONVALIDATIONPROCESS_CONTAINERELEMENTCONSTRAINTS, id = "f")
@SpecAssertion(section = Sections.VALIDATIONAPI_CONSTRAINTVIOLATION, id = "i")
@SpecAssertion(section = Sections.VALIDATIONAPI_CONSTRAINTVIOLATION, id = "ad")
@SpecAssertion(section = Sections.VALIDATIONAPI_CONSTRAINTVIOLATION, id = "ae")
@SpecAssertion(section = Sections.VALIDATIONAPI_CONSTRAINTVIOLATION, id = "ag")
@SpecAssertion(section = Sections.VALIDATIONAPI_CONSTRAINTVIOLATION, id = "ah")
public void validation_of_nested_type_arguments_works_with_map_of_list_of_optional() {
Set<ConstraintViolation<MapOfLists>> constraintViolations = getValidator().validate( MapOfLists.valid() );
assertNoViolations( constraintViolations );
constraintViolations = getValidator().validate( MapOfLists.invalidKey() );
assertThat( constraintViolations ).containsOnlyViolations(
violationOf( Size.class )
.withPropertyPath( pathWith()
.property( "map" )
.containerElement( "<map key>", true, "k", null, Map.class, 0 )
)
.withInvalidValue( MapOfLists.INVALID_KEY )
);
constraintViolations = getValidator().validate( MapOfLists.invalidList() );
assertThat( constraintViolations ).containsOnlyViolations(
violationOf( Size.class )
.withPropertyPath( pathWith()
.property( "map" )
.containerElement( "<map value>", true, "key1", null, Map.class, 1 )
)
.withInvalidValue( MapOfLists.INVALID_LIST )
);
constraintViolations = getValidator().validate( MapOfLists.invalidString() );
assertThat( constraintViolations ).containsOnlyViolations(
violationOf( Size.class )
.withPropertyPath( pathWith()
.property( "map" )
.containerElement( "<map value>", true, "key1", null, Map.class, 1 )
.containerElement( "<list element>", true, null, 0, List.class, 0 )
)
.withInvalidValue( MapOfLists.INVALID_STRING_1 ),
violationOf( Size.class )
.withPropertyPath( pathWith()
.property( "map" )
.containerElement( "<map value>", true, "key1", null, Map.class, 1 )
.containerElement( "<list element>", true, null, 1, List.class, 0 )
)
.withInvalidValue( MapOfLists.INVALID_STRING_2 )
);
constraintViolations = getValidator().validate( MapOfLists.reallyInvalid() );
assertThat( constraintViolations ).containsOnlyViolations(
violationOf( Size.class )
.withPropertyPath( pathWith()
.property( "map" )
.containerElement( "<map key>", true, "k", null, Map.class, 0 )
)
.withInvalidValue( MapOfLists.INVALID_KEY ),
violationOf( Size.class )
.withPropertyPath( pathWith()
.property( "map" )
.containerElement( "<map value>", true, "k", null, Map.class, 1 )
)
.withInvalidValue( MapOfLists.REALLY_INVALID_LIST ),
violationOf( Size.class )
.withPropertyPath( pathWith()
.property( "map" )
.containerElement( "<map value>", true, "k", null, Map.class, 1 )
.containerElement( "<list element>", true, null, 0, List.class, 0 )
)
.withInvalidValue( MapOfLists.INVALID_STRING_1 )
);
}
@Test
@SpecAssertion(section = Sections.CONSTRAINTDECLARATIONVALIDATIONPROCESS_CONTAINERELEMENTCONSTRAINTS, id = "f")
@SpecAssertion(section = Sections.VALIDATIONAPI_CONSTRAINTVIOLATION, id = "ad")
@SpecAssertion(section = Sections.VALIDATIONAPI_CONSTRAINTVIOLATION, id = "ae")
@SpecAssertion(section = Sections.VALIDATIONAPI_CONSTRAINTVIOLATION, id = "af")
@SpecAssertion(section = Sections.VALIDATIONAPI_CONSTRAINTVIOLATION, id = "ag")
@SpecAssertion(section = Sections.VALIDATIONAPI_CONSTRAINTVIOLATION, id = "ah")
public void validation_of_nested_type_arguments_works_with_map_of_list_of_stringproperty() {
Set<ConstraintViolation<MapOfListsWithAutomaticUnwrapping>> constraintViolations = getValidator().validate( MapOfListsWithAutomaticUnwrapping.valid() );
assertNoViolations( constraintViolations );
constraintViolations = getValidator().validate( MapOfListsWithAutomaticUnwrapping.invalidStringProperty() );
assertThat( constraintViolations ).containsOnlyViolations(
violationOf( Min.class )
.withPropertyPath( pathWith()
.property( "map" )
.containerElement( "<map value>", true, "key", null, Map.class, 1 )
.containerElement( "<list element>", true, null, 1, List.class, 0 )
)
);
constraintViolations = getValidator().validate( MapOfListsWithAutomaticUnwrapping.invalidListElement() );
assertThat( constraintViolations ).containsOnlyViolations(
violationOf( NotNull.class )
.withPropertyPath( pathWith()
.property( "map" )
.containerElement( "<map value>", true, "key", null, Map.class, 1 )
.containerElement( "<list element>", true, null, 0, List.class, 0 )
)
);
}
@Test
@SpecAssertion(section = Sections.CONSTRAINTDECLARATIONVALIDATIONPROCESS_CONTAINERELEMENTCONSTRAINTS, id = "f")
public void validation_of_nested_type_arguments_works_on_getter_with_map_of_list_of_optional() {
Set<ConstraintViolation<MapOfListsUsingGetter>> constraintViolations = getValidator().validate( MapOfListsUsingGetter.invalidString() );
assertThat( constraintViolations ).containsOnlyViolations(
violationOf( Size.class )
.withPropertyPath( pathWith()
.property( "map" )
.containerElement( "<map value>", true, "key1", null, Map.class, 1 )
.containerElement( "<list element>", true, null, 0, List.class, 0 )
),
violationOf( Size.class )
.withPropertyPath( pathWith()
.property( "map" )
.containerElement( "<map value>", true, "key1", null, Map.class, 1 )
.containerElement( "<list element>", true, null, 1, List.class, 0 )
)
);
}
@Test
@SpecAssertion(section = Sections.CONSTRAINTDECLARATIONVALIDATIONPROCESS_CONTAINERELEMENTCONSTRAINTS, id = "f")
@SpecAssertion(section = Sections.VALIDATIONAPI_CONSTRAINTVIOLATION, id = "ad")
@SpecAssertion(section = Sections.VALIDATIONAPI_CONSTRAINTVIOLATION, id = "af")
@SpecAssertion(section = Sections.VALIDATIONAPI_CONSTRAINTVIOLATION, id = "ag")
@SpecAssertion(section = Sections.VALIDATIONAPI_CONSTRAINTVIOLATION, id = "ah")
public void validation_of_nested_type_arguments_works_with_list_of_maps() {
Set<ConstraintViolation<ListOfMaps>> constraintViolations = getValidator().validate( ListOfMaps.valid() );
assertNoViolations( constraintViolations );
constraintViolations = getValidator().validate( ListOfMaps.invalidValue() );
assertThat( constraintViolations ).containsOnlyViolations(
violationOf( Size.class )
.withPropertyPath( pathWith()
.property( "list" )
.containerElement( "<list element>", true, null, 0, List.class, 0 )
.containerElement( "<map value>", true, "key", null, Map.class, 1 )
)
);
}
@Test
@SpecAssertion(section = Sections.CONSTRAINTDECLARATIONVALIDATIONPROCESS_CONTAINERELEMENTCONSTRAINTS, id = "f")
@SpecAssertion(section = Sections.VALIDATIONAPI_CONSTRAINTVIOLATION, id = "ad")
@SpecAssertion(section = Sections.VALIDATIONAPI_CONSTRAINTVIOLATION, id = "ag")
@SpecAssertion(section = Sections.VALIDATIONAPI_CONSTRAINTVIOLATION, id = "ah")
public void validation_of_nested_type_arguments_works_with_list_of_iterables() {
Set<ConstraintViolation<ListOfIterables>> constraintViolations = getValidator().validate( ListOfIterables.valid() );
assertNoViolations( constraintViolations );
constraintViolations = getValidator().validate( ListOfIterables.invalid() );
assertThat( constraintViolations ).containsOnlyViolations(
violationOf( Size.class )
.withPropertyPath( pathWith()
.property( "list" )
.containerElement( "<list element>", true, null, 0, List.class, 0 )
.containerElement( "<iterable element>", true, null, null, Set.class, 0 )
)
);
}
private static class MapOfLists {
private static final String INVALID_KEY = "k";
private static final List<Optional<String>> INVALID_LIST = Arrays.asList( Optional.of( "only one value" ) );
private static final String INVALID_STRING_1 = "1";
private static final String INVALID_STRING_2 = "2";
private static final List<Optional<String>> REALLY_INVALID_LIST = Arrays.asList( Optional.of( INVALID_STRING_1 ) );
private Map<@Size(min = 2) String, @NotNull @Size(min = 2) List<Optional<@Size(min = 3) String>>> map;
private static MapOfLists valid() {
MapOfLists foo = new MapOfLists();
List<Optional<String>> list = Arrays.asList( Optional.of( "one" ), Optional.of( "two" ) );
foo.map = new HashMap<>();
foo.map.put( "key", list );
return foo;
}
private static MapOfLists invalidKey() {
MapOfLists foo = new MapOfLists();
List<Optional<String>> list = Arrays.asList( Optional.of( "one" ), Optional.of( "two" ) );
foo.map = new HashMap<>();
foo.map.put( INVALID_KEY, list );
return foo;
}
private static MapOfLists invalidList() {
MapOfLists foo = new MapOfLists();
List<Optional<String>> list = Arrays.asList( Optional.of( "only one value" ) );
foo.map = new HashMap<>();
foo.map.put( "key1", list );
return foo;
}
private static MapOfLists invalidString() {
MapOfLists foo = new MapOfLists();
List<Optional<String>> list = Arrays.asList( Optional.of( INVALID_STRING_1 ), Optional.of( INVALID_STRING_2 ) );
foo.map = new HashMap<>();
foo.map.put( "key1", list );
return foo;
}
private static MapOfLists reallyInvalid() {
MapOfLists foo = new MapOfLists();
foo.map = new HashMap<>();
foo.map.put( INVALID_KEY, REALLY_INVALID_LIST );
return foo;
}
}
private static class MapOfListsUsingGetter {
private Map<String, List<Optional<String>>> map;
static MapOfListsUsingGetter invalidString() {
MapOfListsUsingGetter mapOfListsUsingGetter = new MapOfListsUsingGetter();
mapOfListsUsingGetter.map = MapOfLists.invalidString().map;
return mapOfListsUsingGetter;
}
@SuppressWarnings("unused")
Map<@Size(min = 2) String, @NotNull @Size(min = 2) List<Optional<@Size(min = 3) String>>> getMap() {
return map;
}
}
private static class MapOfListsWithAutomaticUnwrapping {
private Map<@Size(min = 2) String, List<@NotNull(payload = { Unwrapping.Skip.class }) @Min(2) OptionalInt>> map;
private static MapOfListsWithAutomaticUnwrapping valid() {
MapOfListsWithAutomaticUnwrapping bar = new MapOfListsWithAutomaticUnwrapping();
List<OptionalInt> list = Arrays.asList( OptionalInt.of( 3 ), OptionalInt.of( 4 ),
OptionalInt.of( 5 ) );
bar.map = new HashMap<>();
bar.map.put( "key", list );
return bar;
}
private static MapOfListsWithAutomaticUnwrapping invalidStringProperty() {
MapOfListsWithAutomaticUnwrapping bar = new MapOfListsWithAutomaticUnwrapping();
List<OptionalInt> list = Arrays.asList( OptionalInt.of( 3 ), OptionalInt.of( 1 ),
OptionalInt.of( 5 ) );
bar.map = new HashMap<>();
bar.map.put( "key", list );
return bar;
}
private static MapOfListsWithAutomaticUnwrapping invalidListElement() {
MapOfListsWithAutomaticUnwrapping bar = new MapOfListsWithAutomaticUnwrapping();
List<OptionalInt> list = Arrays.asList( null, OptionalInt.of( 3 ) );
bar.map = new HashMap<>();
bar.map.put( "key", list );
return bar;
}
}
private static class ListOfMaps {
private List<Map<@Size(min = 2) String, @NotNull @Size(min = 2) String>> list;
private static ListOfMaps valid() {
ListOfMaps foo = new ListOfMaps();
Map<String, String> map = new HashMap<>();
map.put( "key", "value" );
foo.list = new ArrayList<>();
foo.list.add( map );
return foo;
}
private static ListOfMaps invalidValue() {
ListOfMaps foo = new ListOfMaps();
Map<String, String> map = new HashMap<>();
map.put( "key", "v" );
foo.list = new ArrayList<>();
foo.list.add( map );
return foo;
}
}
private static class ListOfIterables {
private List<Set<@Size(min = 2) String>> list;
private static ListOfIterables valid() {
ListOfIterables foo = new ListOfIterables();
Set<String> set = new HashSet<>();
set.add( "value" );
foo.list = new ArrayList<>();
foo.list.add( set );
return foo;
}
private static ListOfIterables invalid() {
ListOfIterables foo = new ListOfIterables();
Set<String> set = new HashSet<>();
set.add( "v" );
foo.list = new ArrayList<>();
foo.list.add( set );
return foo;
}
}
}
|
package am.extension.userfeedback.experiments;
import java.awt.event.ActionEvent;
import am.extension.userfeedback.UFLExperiment;
import am.extension.userfeedback.ui.UFLControlGUI.ActionCommands;
public class IndependentSequentialLogic extends UFLControlLogic {
@Override
public void runExperiment(UFLExperiment exp) {
this.experiment = exp;
runInitialMatchers();
}
/* actionPerformed. Almost all the real work is done here. */
public void actionPerformed(ActionEvent e) {
System.out.println(e.getActionCommand()); // TODO: Remove this.
if( experiment != null && experiment.experimentHasCompleted() ) { // check stop condition
System.out.println("Experiment has completed. Ignoring further actions.");
}
if( e.getActionCommand() == ActionCommands.EXECUTION_SEMANTICS_DONE.name() ) {
runCandidateSelection();
}
if( e.getActionCommand() == ActionCommands.CANDIDATE_SELECTION_DONE.name() ) {
runCandidateSelectionEvaluation();
}
if( e.getActionCommand() == ActionCommands.CS_EVALUATION_DONE.name() ) {
runUserValidation();
}
if( e.getActionCommand() == ActionCommands.USER_FEEDBACK_DONE.name() ) {
runFeedbackPropagation();
}
if( e.getActionCommand() == ActionCommands.PROPAGATION_DONE.name() ) {
runPropagationEvaluation();
}
if( e.getActionCommand() == ActionCommands.PROPAGATION_EVALUATION_DONE.name() ) {
experiment.newIteration();
runCandidateSelection(); // back to top /\
}
}
}
|
package org.eclipse.smarthome.binding.dmx;
import static org.eclipse.smarthome.binding.dmx.DmxBindingConstants.*;
import static org.hamcrest.core.Is.is;
import static org.junit.Assert.*;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.*;
import java.util.HashMap;
import java.util.Map;
import org.eclipse.smarthome.binding.dmx.internal.DmxBridgeHandler;
import org.eclipse.smarthome.binding.dmx.internal.multiverse.BaseDmxChannel;
import org.eclipse.smarthome.binding.dmx.internal.multiverse.Universe;
import org.eclipse.smarthome.config.core.Configuration;
import org.eclipse.smarthome.core.library.types.OnOffType;
import org.eclipse.smarthome.core.thing.Bridge;
import org.eclipse.smarthome.core.thing.ChannelUID;
import org.eclipse.smarthome.core.thing.Thing;
import org.eclipse.smarthome.core.thing.ThingStatus;
import org.eclipse.smarthome.core.thing.ThingTypeUID;
import org.eclipse.smarthome.core.thing.ThingUID;
import org.eclipse.smarthome.core.thing.binding.ThingHandlerCallback;
import org.eclipse.smarthome.core.thing.binding.builder.BridgeBuilder;
import org.eclipse.smarthome.core.thing.binding.builder.ChannelBuilder;
import org.eclipse.smarthome.core.thing.binding.builder.ThingBuilder;
import org.eclipse.smarthome.test.java.JavaTest;
import org.junit.After;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
import org.mockito.Mockito;
/**
* Tests cases for {@link DmxBridgeHandler}.
*
* @author Jan N. Klug - Initial contribution
*/
public class DmxBridgeHandlerTest extends JavaTest {
/**
* simple DmxBridgeHandlerImplementation
*
* @author Jan N. Klug
*
*/
public class DmxBridgeHandlerImpl extends DmxBridgeHandler {
public DmxBridgeHandlerImpl(Bridge dmxBridge) {
super(dmxBridge);
}
@Override
public void openConnection() {
}
@Override
protected void sendDmxData() {
}
@Override
protected void closeConnection() {
}
@Override
public void initialize() {
universe = new Universe(TEST_UNIVERSE);
super.updateConfiguration();
updateStatus(ThingStatus.ONLINE);
}
}
private static final int TEST_UNIVERSE = 1;
private static final int TEST_CHANNEL = 100;
private final ThingTypeUID THING_TYPE_TEST_BRIDGE = new ThingTypeUID(BINDING_ID, "testbridge");
private final ThingUID BRIDGE_UID_TEST = new ThingUID(THING_TYPE_TEST_BRIDGE, "testbridge");
private final ChannelUID CHANNEL_UID_MUTE = new ChannelUID(BRIDGE_UID_TEST, CHANNEL_MUTE);
Map<String, Object> bridgeProperties;
private Bridge bridge;
private DmxBridgeHandlerImpl bridgeHandler;
@Before
public void setUp() {
bridgeProperties = new HashMap<>();
bridge = BridgeBuilder.create(THING_TYPE_TEST_BRIDGE, "testbridge").withLabel("Test Bridge")
.withChannel(ChannelBuilder.create(CHANNEL_UID_MUTE, "Switch").withType(MUTE_CHANNEL_TYPEUID).build())
.withConfiguration(new Configuration(bridgeProperties)).build();
ThingHandlerCallback mockCallback = mock(ThingHandlerCallback.class);
doAnswer(answer -> {
((Thing) answer.getArgument(0)).setStatusInfo(answer.getArgument(1));
return null;
}).when(mockCallback).statusUpdated(any(), any());
bridgeHandler = Mockito.spy(new DmxBridgeHandlerImpl(bridge));
bridgeHandler.getThing().setHandler(bridgeHandler);
bridgeHandler.setCallback(mockCallback);
bridgeHandler.initialize();
}
@After
public void tearDown() {
bridgeHandler.dispose();
}
@Test
public void assertBridgeStatus() {
waitForAssert(() -> assertEquals(ThingStatus.ONLINE, bridge.getStatusInfo().getStatus()));
}
@Ignore("https://github.com/eclipse/smarthome/issues/6015#issuecomment-411313627")
@Test
public void assertSendDmxDataIsCalled() {
Mockito.verify(bridgeHandler, after(500).atLeast(9)).sendDmxData();
}
@Ignore("https://github.com/eclipse/smarthome/issues/6015")
@Test
public void assertMuteChannelMutesOutput() {
bridgeHandler.handleCommand(CHANNEL_UID_MUTE, OnOffType.ON);
Mockito.verify(bridgeHandler, after(500).atMost(1)).sendDmxData();
bridgeHandler.handleCommand(CHANNEL_UID_MUTE, OnOffType.OFF);
Mockito.verify(bridgeHandler, after(500).atLeast(9)).sendDmxData();
}
@Test
public void assertRetrievingOfChannels() {
BaseDmxChannel channel = new BaseDmxChannel(TEST_UNIVERSE, TEST_CHANNEL);
BaseDmxChannel returnedChannel = bridgeHandler.getDmxChannel(channel,
ThingBuilder.create(THING_TYPE_DIMMER, "testthing").build());
Integer channelId = returnedChannel.getChannelId();
assertThat(channelId, is(TEST_CHANNEL));
}
}
|
// Triple Play - utilities for use in PlayN-based games
package tripleplay.ui;
import pythagoras.f.Dimension;
import pythagoras.f.IPoint;
import pythagoras.f.IRectangle;
import pythagoras.f.Point;
import pythagoras.f.Rectangle;
import playn.core.Connection;
import playn.core.Events;
import playn.core.GroupLayer;
import playn.core.Layer;
import playn.core.Pointer;
import react.Slot;
import tripleplay.ui.Style.HAlign;
import tripleplay.ui.Style.VAlign;
import tripleplay.util.Layers;
import static playn.core.PlayN.*;
import static tripleplay.ui.Log.log;
/**
* Provides a context for popping up a menu.
*/
public class MenuHost
{
/** The root layer that will contain all menus that pop up. It should normally be close to the
* top of the hierarchy so that it draws on top of everything. */
public final GroupLayer rootLayer;
/** The interface we use to create the menu's root and do animation. */
public final Interface iface;
/**
* An event type for triggering a menu popup. Also acts as a menu constraint so the integrated
* host layout can make sure the whole menu is on screen and near to the triggering event
* position or element.
*/
public static class Pop extends Layout.Constraint
{
/** The element that triggered the popup. {@link #position} is relative to this. */
public final Element<?> trigger;
/** The menu to show. */
public final Menu menu;
/** The position where the menu should pop up, e.g. a touch event position. Relative to
* {@link #trigger}. */
public IPoint position;
/** The bounds to confine the menu, in screen coordinates; usually the whole screen. */
public IRectangle bounds;
/** Creates a new event and initializes {@link #trigger} and {@link #menu}. */
public Pop (Element<?> trigger, Menu menu) {
if (menu == null) throw new IllegalArgumentException();
this.menu = menu;
this.trigger = trigger;
position = new Point(0, 0);
}
/**
* Causes the menu to handle further events on the given layer. This is usually the layer
* handling a pointer start that caused the popup. A listener will be added to the layer
* and the menu notified of pointer drag and end events.
*/
public Pop relayEvents (Layer layer) {
_relayTarget = layer;
return this;
}
/**
* Positions the menu popup at the given positional event.
*/
public Pop atEventPos (Events.Position pos) {
return atScreenPos(pos.x(), pos.y());
}
/**
* Positions the menu popup at the given screen position.
*/
public Pop atScreenPos (float x, float y) {
position = new Point(x, y);
return this;
}
/**
* Positions the menu horizontally relative to the given layer, with an offset. The
* vertical position remains unchanged.
*/
public Pop atLayerX (Layer layer, float x) {
return atScreenPos(Layer.Util.layerToScreen(layer, x, 0).x, position.y());
}
/**
* Positions the menu vertically relative to the given layer, with an offset. The
* horizontal position remains unchanged.
*/
public Pop atLayerY (Layer layer, float y) {
return atScreenPos(position.x(), Layer.Util.layerToScreen(layer, 0, y).y);
}
/**
* Sets the horizontal alignment of the menu relative to the popup position.
*/
public Pop halign (HAlign halign) {
_halign = halign;
return this;
}
/**
* Sets the vertical alignment of the menu relative to the popup position.
*/
public Pop valign (VAlign valign) {
_valign = valign;
return this;
}
/**
* Positions the right edge of the menu relative to the left edge of the trigger, offset
* by the given value.
*/
public Pop toLeft (float x) {
return atLayerX(trigger.layer, x).halign(HAlign.RIGHT);
}
/**
* Positions the left edge of the menu relative to the right edge of the trigger, offset
* by the given value.
*/
public Pop toRight (float x) {
return atLayerX(trigger.layer, trigger.size().width() + x).halign(HAlign.LEFT);
}
/**
* Positions the top edge of the menu relative to the top edge of the trigger, offset
* by the given value.
*/
public Pop toTop (float y) {
return atLayerY(trigger.layer, y).valign(VAlign.TOP);
}
/**
* Positions the bottom edge of the menu relative to the bottom edge of the trigger, offset
* by the given value.
*/
public Pop toBottom (float y) {
return atLayerY(trigger.layer, trigger.size().height() + y).valign(VAlign.BOTTOM);
}
/**
* Flags this {@code Pop} event so that the menu will not be destroyed automatically when
* it is deactivated. Returns this instance for chaining.
*/
public Pop retainMenu () {
_retain = true;
return this;
}
/**
* Optionally confines the menu area to the given screen area. By default the menu is
* confined by the host's screen area (see {@link MenuHost#getScreenArea()}).
*/
public Pop inScreenArea (IRectangle area) {
bounds = new Rectangle(area);
return this;
}
/**
* Optionally confines the menu area to the given element. By default the menu is confined
* by the host's screen area (see {@link MenuHost#getScreenArea()}).
*/
public Pop inElement (Element<?> elem) {
Point tl = Layer.Util.layerToScreen(elem.layer, 0, 0);
Point br = Layer.Util.layerToScreen(elem.layer, elem.size().width(), elem.size().height());
bounds = new Rectangle(tl.x(), tl.y(), br.x() - tl.x(), br.y() - tl.y());
return this;
}
/**
* Pops up this instance on the trigger's root's menu host. See {@link MenuHost#popup(Pop)}.
* For convenience, returns the host that was used to perform the popup.
*/
public MenuHost popup () {
Root root = trigger.root();
if (root == null) {
Log.log.warning("Menu trigger not on a root?", "trigger", trigger);
return null;
}
root.getMenuHost().popup(this);
return root.getMenuHost();
}
/** Whether we should keep the menu around (i.e. not destroy it). */
protected boolean _retain;
/** The layer that will be sending pointer drag and end events to us. */
protected Layer _relayTarget;
protected HAlign _halign = HAlign.LEFT;
protected VAlign _valign = VAlign.TOP;
}
public static Connection relayEvents (Layer from, final Menu to) {
return from.addListener(new Pointer.Adapter() {
@Override public void onPointerDrag (Pointer.Event e) { to.onPointerDrag(e); }
@Override public void onPointerEnd (Pointer.Event e) { to.onPointerEnd(e); }
});
}
/**
* Creates a menu host using the given values. The root layer is set to the layer of the given
* root and the stylesheet to its stylesheet.
*/
public MenuHost (Interface iface, Elements<?> root) {
this(iface, root.layer);
_stylesheet = root.stylesheet();
}
/**
* Creates a new menu host using the given values. The stylesheet is set to an empty
* one and can be changed via the {@link #setStylesheet(Stylesheet)} method.
*/
public MenuHost (Interface iface, GroupLayer rootLayer) {
this.iface = iface;
this.rootLayer = rootLayer;
}
/**
* Sets the stylesheet for menus popped by this host.
*/
public MenuHost setStylesheet (Stylesheet sheet) {
_stylesheet = sheet;
return this;
}
/**
* Deactivates the current menu, if any is showing.
*/
public void deactivate () {
if (_active != null) {
_active.pop.menu.deactivate();
}
}
/**
* Sets the area to which menus should be confined when there isn't any other associated
* bounds.
*/
public void setScreenArea (IRectangle screenArea) {
_screenArea.setBounds(screenArea);
}
/**
* Gets the area to which menus should be confined when there isn't any other associated
* bounds. By default, the entire available area is used, as given by
* {@link playn.core.Graphics}.
*/
public IRectangle getScreenArea () {
return _screenArea;
}
/**
* Displays the menu specified by the given pop, incorporating all the configured attributes
* therein.
*/
public void popup (final Pop pop) {
// if there is no explicit constraint area requested, use the graphics
if (pop.bounds == null) pop.inScreenArea(_screenArea);
// set up the menu root, the RootLayout will do the complicated bounds jockeying
final Root menuRoot = iface.createRoot(new RootLayout(), _stylesheet, rootLayer);
menuRoot.layer.setDepth(1);
menuRoot.layer.setHitTester(null); // get hits from out of bounds
menuRoot.add(pop.menu.setConstraint(pop));
menuRoot.pack();
menuRoot.layer.setTranslation(pop.position.x(), pop.position.y());
// set up the activation
final Activation activation = new Activation(pop);
// cleanup
final Runnable cleanup = new Runnable() {
@Override public void run () {
// check parentage, it's possible the menu has been repopped already
if (pop.menu.parent() == menuRoot) {
// free the constraint to gc
pop.menu.setConstraint(null);
// remove or destroy it, depending on the caller's preference
if (pop._retain) menuRoot.remove(pop.menu);
else menuRoot.destroy(pop.menu);
// remove the hidden area we added
uiOverlay().hideOverlay(null);
}
// clear all connections
activation.clear();
// always kill off the transient root
iface.destroyRoot(menuRoot);
// if this was our active menu, clear it
if (_active != null && _active.pop == pop) _active = null;
}
};
// connect to deactivation signal and do our cleanup
activation.deactivated = pop.menu.deactivated().connect(new Slot<Menu>() {
@Override public void onEmit (Menu event) {
// due to animations, deactivation can happen during layout, so do it next frame
invokeLater(cleanup);
}
});
// close the menu any time the trigger is removed from the hierarchy
activation.triggerRemoved = pop.trigger.hierarchyChanged().connect(new Slot<Boolean>() {
@Override public void onEmit (Boolean event) {
if (!event) pop.menu.deactivate();
}
});
// deactivate the old menu
if (_active != null) _active.pop.menu.deactivate();
// pass along the animator
pop.menu.init(iface.animator());
// activate
_active = activation;
pop.menu.activate();
}
public Pop activePop () {
return _active != null ? _active.pop : null;
}
public Menu active () {
return _active != null ? _active.pop.menu : null;
}
/** Simple layout for positioning the menu within the transient {@code Root}. */
protected static class RootLayout extends Layout
{
@Override public Dimension computeSize (Container<?> elems, float hintX, float hintY) {
return new Dimension(preferredSize(elems.childAt(0), hintX, hintY));
}
@Override public void layout (Container<?> elems, float left, float top, float width,
float height) {
if (elems.childCount() == 0) return;
// get the constraint, it will always be a Pop
Pop pop = (Pop)elems.childAt(0).constraint();
// figure out the best place to put the menu, in screen coordinates; starting with
// the requested popup position
Rectangle bounds = new Rectangle(
pop.position.x() + pop._halign.offset(width, 0),
pop.position.y() + pop._valign.offset(height, 0), width, height);
// make sure the menu lies inside the requested bounds if the menu doesn't do
// that itself
if (pop.menu.automaticallyConfine()) {
confine(pop.bounds, bounds);
// fudge is the number of pixels around the menu that we don't need to avoid
// TODO: can we get the menu's Background's insets?
float fudge = 2;
// keep the bounds from overlapping the position
if (bounds.width > fudge * 2 && bounds.height > fudge * 2) {
Rectangle ibounds = new Rectangle(bounds);
ibounds.grow(-fudge, -fudge);
// set up the fingerprint
float fingerRadius = touch().hasTouch() ? 10 : 3;
Rectangle fingerBox = new Rectangle(
pop.position.x() - fingerRadius, pop.position.y() - fingerRadius,
fingerRadius * 2, fingerRadius * 2);
// try and place the menu so it isn't under the finger
if (!avoidPoint(pop.bounds, ibounds, fingerBox)) {
log.warning("Oh god, menu doesn't fit", "menu", pop.menu);
}
bounds.setLocation(ibounds.x() - fudge, ibounds.y() - fudge);
}
}
// save a copy of bounds in screen coordinates
Rectangle screenBounds = new Rectangle(bounds);
// relocate to layer coordinates
bounds.setLocation(Layer.Util.screenToLayer(elems.layer, bounds.x, bounds.y));
// set the menu bounds
setBounds(elems.childAt(0), bounds.x, bounds.y, bounds.width, bounds.height);
// check if menu is closed (layout can still occur in this state)
if (!pop.menu._defunct) {
// tell the UI overlay to let the real dimensions of the menu through
// TODO: this looks wrong if the menu has any transparent border - fix
// by using an image overlay instead, with the root captured onto it
uiOverlay().hideOverlay(screenBounds);
}
}
}
/** Tries to place the inner bounds within the outer bounds, such that the inner bounds does
* not contain the position. */
protected static boolean avoidPoint (IRectangle outer, Rectangle inner, IRectangle fingerprint)
{
Rectangle checkBounds = new Rectangle();
Rectangle best = new Rectangle(inner);
float bestDist = Float.MAX_VALUE, edge;
// confine to the left
edge = fingerprint.x();
checkBounds.setBounds(outer.x(), outer.y(), edge - outer.x(), outer.height());
bestDist = compareAndConfine(checkBounds, inner, best, bestDist);
// right
edge = fingerprint.maxX();
checkBounds.setBounds(edge, outer.y(), outer.width() - edge, outer.height());
bestDist = compareAndConfine(checkBounds, inner, best, bestDist);
// top
edge = fingerprint.y();
checkBounds.setBounds(outer.x(), outer.y(), outer.width(), edge - outer.y());
bestDist = compareAndConfine(checkBounds, inner, best, bestDist);
// bottom
edge = fingerprint.maxY();
checkBounds.setBounds(outer.x(), edge, outer.width(), outer.height() - edge);
bestDist = compareAndConfine(checkBounds, inner, best, bestDist);
inner.setBounds(best);
return bestDist < Float.MAX_VALUE;
}
/** Confines a rectangle and updates the current best fit based on the moved distance. */
protected static float compareAndConfine (
IRectangle outer, IRectangle inner, Rectangle best, float bestDist) {
// don't bother if there isn't even enough space
if (outer.width() <= inner.width() || outer.height() < inner.height()) return bestDist;
// confine
Rectangle confined = confine(outer, new Rectangle(inner));
// check distance and overwrite the best fit if we have a new winner
float dx = confined.x - inner.x(), dy = confined.y - inner.y();
float dist = dx * dx + dy * dy;
if (dist < bestDist) {
best.setBounds(confined);
bestDist = dist;
}
return bestDist;
}
/** Moves ths given inner rectangle such that it lies within the given outer rectangle.
* The results are undefined if either the inner width or height is greater that the outer's
* width or height, respectively. */
protected static Rectangle confine (IRectangle outer, Rectangle inner) {
float dx = outer.x() - inner.x(), dy = outer.y() - inner.y();
if (dx <= 0) dx = Math.min(0, outer.maxX() - inner.maxX());
if (dy <= 0) dy = Math.min(0, outer.maxY() - inner.maxY());
inner.translate(dx, dy);
return inner;
}
/** Holds a few variables related to the menu's activation. */
protected static class Activation
{
/** The configuration of the menu. */
public final Pop pop;
/** Connects to the pointer events from the relay. */
public Connection pointerRelay = Layers.NOT_LISTENING;
/** Connection to the trigger's hierarchy change. */
public react.Connection triggerRemoved;
/** Connection to the menu's deactivation. */
public react.Connection deactivated;
/** Creates a new activation. */
public Activation (Pop pop) {
this.pop = pop;
// handle pointer events from the relay
Layer target = pop._relayTarget;
if (target != null) pointerRelay = relayEvents(target, pop.menu);
}
/** Clears out the connections. */
public void clear () {
if (triggerRemoved != null) triggerRemoved.disconnect();
if (deactivated != null) deactivated.disconnect();
pointerRelay.disconnect();
pointerRelay = null;
triggerRemoved = null;
deactivated = null;
}
}
/** The stylesheet used for popped menus. */
protected Stylesheet _stylesheet = Stylesheet.builder().create();
/** Currently active. */
protected Activation _active;
/** When confining the menu to the graphics' bounds, use this. */
protected final Rectangle _screenArea = new Rectangle(
0, 0, graphics().width(), graphics().height());
}
|
package org.egordorichev.lasttry;
import com.badlogic.gdx.Game;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import org.egordorichev.lasttry.core.Version;
import org.egordorichev.lasttry.core.Crash;
import org.egordorichev.lasttry.graphics.*;
import org.egordorichev.lasttry.input.InputManager;
import org.egordorichev.lasttry.item.Item;
import org.egordorichev.lasttry.item.Items;
import org.egordorichev.lasttry.language.LocalizationUtil;
import org.egordorichev.lasttry.state.SplashState;
import org.egordorichev.lasttry.ui.UiManager;
import org.egordorichev.lasttry.util.Camera;
import org.egordorichev.lasttry.util.Debug;
import org.egordorichev.lasttry.language.Language;
import java.util.Random;
import java.util.Locale;
/** Main game class */
public class LastTry extends Game {
/** LastTry version */
public static final Version version = new Version(0.0, 13, "alpha");
/** Random instance */
public static final Random random = new Random();
/** Last Try instance */
public static LastTry instance;
/** Ui manager */
public static UiManager ui;
/** Debug helper */
public static Debug debug;
/** Shows, if this is a release */
public static boolean release = true;
/** Creates first-priority instances */
@Override
public void create() {
//TODO: Just for testing
//LocalizationUtil.localize(Items.class, Item.class);
Thread.currentThread().setUncaughtExceptionHandler((thread, throwable) -> Crash.report(thread, throwable));
instance = this;
Camera.create(800, 600);
Language.load(new Locale("en", "US"));
Gdx.input.setInputProcessor(InputManager.multiplexer);
Gdx.graphics.setTitle(this.getRandomWindowTitle());
Graphics.batch = new SpriteBatch();
debug = new Debug();
ui = new UiManager();
this.setScreen(new SplashState());
}
/**
* Handles window resize
* @param width new window width
* @param height new window height
*/
@Override
public void resize(int width, int height) {
super.resize(width, height);
Camera.resize(width, height);
}
/** Renders and updates the game */
@Override
public void render() {
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
Gdx.gl.glClearColor(0, 0, 0, 1);
Graphics.batch.enableBlending();
Graphics.batch.begin();
super.render();
Graphics.batch.end();
}
/** Handles game exit */
@Override
public void dispose() {
Globals.dispose();
Assets.dispose();
}
/**
* Returns random title for game the window
* @return random title for game the window
*/
private String getRandomWindowTitle() {
String[] split = Language.text.get("windowTitles").split("
return split[random.nextInt(split.length)] + " " + version.toString();
}
/**
* Returns mouse X coordinate, under the world
* @return mouse X coordinate, under the world
*/
public static int getMouseXInWorld() {
return (int) (Globals.player.physics.getCenterX() - Gdx.graphics.getWidth() / 2 + InputManager.getMousePosition().x);
}
/**
* Returns mouse Y coordinate, under the world
* @return mouse Y coordinate, under the world
*/
public static int getMouseYInWorld() {
return (int) (Globals.player.physics.getCenterY() + Gdx.graphics.getHeight() / 2 - InputManager.getMousePosition().y);
}
/**
* Handles exception, if it is critical, exits the game
* @param exception exception to handle
*/
public static void handleException(Exception exception) {
Crash.report(Thread.currentThread(), exception);
}
public static void abort() {
System.exit(1);
}
}
|
package util;
import com.sun.star.accessibility.XAccessible;
import com.sun.star.accessibility.XAccessibleComponent;
import com.sun.star.accessibility.XAccessibleContext;
import com.sun.star.accessibility.XAccessibleRelationSet;
import com.sun.star.accessibility.XAccessibleStateSet;
import com.sun.star.awt.XWindow;
import com.sun.star.frame.XController;
import com.sun.star.frame.XDesktop;
import com.sun.star.frame.XFrame;
import com.sun.star.frame.XModel;
import com.sun.star.lang.XMultiServiceFactory;
import com.sun.star.uno.UnoRuntime;
import com.sun.star.uno.XInterface;
import java.io.PrintWriter;
public class AccessibilityTools {
public static XAccessibleContext SearchedContext = null;
public static XAccessible SearchedAccessible = null;
private static boolean debug = false;
public AccessibilityTools() {
//done = false;
SearchedContext = null;
}
public static XAccessible getAccessibleObject(XInterface xObject) {
XAccessible xAccessible = null;
try {
xAccessible = (XAccessible) UnoRuntime.queryInterface(
XAccessible.class, xObject);
} catch (Exception e) {
System.out.println(
"caught exception while getting accessible object" + e);
e.printStackTrace();
}
return xAccessible;
}
public static XWindow getCurrentContainerWindow(XMultiServiceFactory msf,
XModel xModel) {
return getWindow(msf, xModel, true);
}
public static XWindow getCurrentWindow(XMultiServiceFactory msf,
XModel xModel) {
return getWindow(msf, xModel, false);
}
private static XWindow getWindow(XMultiServiceFactory msf, XModel xModel,
boolean containerWindow) {
XWindow xWindow = null;
try {
if (xModel == null) {
System.out.println("invalid model (==null)");
}
XController xController = xModel.getCurrentController();
if (xController == null) {
System.out.println("can't get controller from model");
}
XFrame xFrame = xController.getFrame();
if (xFrame == null) {
System.out.println("can't get frame from controller");
}
if (containerWindow)
xWindow = xFrame.getContainerWindow();
else
xWindow = xFrame.getComponentWindow();
if (xWindow == null) {
System.out.println("can't get window from frame");
}
} catch (Exception e) {
System.out.println("caught exception while getting current window" + e);
}
return xWindow;
}
public static XAccessibleContext getAccessibleObjectForRole(XAccessible xacc,
short role) {
SearchedContext = null;
SearchedAccessible = null;
getAccessibleObjectForRole_(xacc, role);
return SearchedContext;
}
public static XAccessibleContext getAccessibleObjectForRole(XAccessible xacc,
short role,
boolean ignoreShowing) {
SearchedContext = null;
SearchedAccessible = null;
if (ignoreShowing) {
getAccessibleObjectForRoleIgnoreShowing_(xacc, role);
} else {
getAccessibleObjectForRole_(xacc, role);
}
return SearchedContext;
}
public static void getAccessibleObjectForRoleIgnoreShowing_(XAccessible xacc,
short role) {
XAccessibleContext ac = xacc.getAccessibleContext();
if (ac.getAccessibleRole() == role) {
SearchedContext = ac;
SearchedAccessible = xacc;
} else {
int k = ac.getAccessibleChildCount();
if (ac.getAccessibleChildCount() > 100) {
k = 50;
}
for (int i = 0; i < k; i++) {
try {
getAccessibleObjectForRoleIgnoreShowing_(
ac.getAccessibleChild(i), role);
if (SearchedContext != null) {
return;
}
} catch (com.sun.star.lang.IndexOutOfBoundsException e) {
System.out.println("Couldn't get Child");
}
}
}
}
public static void getAccessibleObjectForRole_(XAccessible xacc,
short role) {
XAccessibleContext ac = xacc.getAccessibleContext();
boolean isShowing = ac.getAccessibleStateSet()
.contains(com.sun.star.accessibility.AccessibleStateType.SHOWING);
if ((ac.getAccessibleRole() == role) && isShowing) {
SearchedContext = ac;
SearchedAccessible = xacc;
} else {
int k = ac.getAccessibleChildCount();
if (ac.getAccessibleChildCount() > 100) {
k = 50;
}
for (int i = 0; i < k; i++) {
try {
getAccessibleObjectForRole_(ac.getAccessibleChild(i), role);
if (SearchedContext != null) {
return;
}
} catch (com.sun.star.lang.IndexOutOfBoundsException e) {
System.out.println("Couldn't get Child");
}
}
}
}
public static XAccessibleContext getAccessibleObjectForRole(XAccessible xacc,
short role,
String name) {
return getAccessibleObjectForRole(xacc, role, name, "");
}
public static XAccessibleContext getAccessibleObjectForRole(XAccessible xacc,
short role,
String name,
boolean ignoreShowing) {
if (ignoreShowing) {
return getAccessibleObjectForRoleIgnoreShowing(xacc, role, name,
"");
} else {
return getAccessibleObjectForRole(xacc, role, name, "");
}
}
public static XAccessibleContext getAccessibleObjectForRoleIgnoreShowing(XAccessible xacc,
short role,
String name,
String implName) {
XAccessibleContext ac = xacc.getAccessibleContext();
if ((ac.getAccessibleRole() == role) &&
(ac.getAccessibleName().indexOf(name) > -1) &&
(utils.getImplName(ac).indexOf(implName) > -1)) {
SearchedAccessible = xacc;
//System.out.println("FOUND the desired component -- "+ ac.getAccessibleName() +isShowing);
return ac;
} else {
int k = ac.getAccessibleChildCount();
if (ac.getAccessibleChildCount() > 100) {
k = 50;
}
for (int i = 0; i < k; i++) {
try {
XAccessibleContext ac1 = getAccessibleObjectForRoleIgnoreShowing(
ac.getAccessibleChild(i),
role, name, implName);
if (ac1 != null) {
return ac1;
}
} catch (com.sun.star.lang.IndexOutOfBoundsException e) {
System.out.println("Couldn't get Child");
}
}
}
return null;
}
public static XAccessibleContext getAccessibleObjectForRole(XAccessible xacc,
short role,
String name,
String implName) {
XAccessibleContext ac = xacc.getAccessibleContext();
boolean isShowing = ac.getAccessibleStateSet()
.contains(com.sun.star.accessibility.AccessibleStateType.SHOWING);
if ((ac.getAccessibleRole() == role) &&
(ac.getAccessibleName().indexOf(name) > -1) &&
(utils.getImplName(ac).indexOf(implName) > -1) &&
isShowing) {
SearchedAccessible = xacc;
//System.out.println("FOUND the desired component -- "+ ac.getAccessibleName() +isShowing);
return ac;
} else {
int k = ac.getAccessibleChildCount();
if (ac.getAccessibleChildCount() > 100) {
k = 50;
}
for (int i = 0; i < k; i++) {
try {
XAccessibleContext ac1 = getAccessibleObjectForRole(
ac.getAccessibleChild(i),
role, name, implName);
if (ac1 != null) {
return ac1;
}
} catch (com.sun.star.lang.IndexOutOfBoundsException e) {
System.out.println("Couldn't get Child");
}
}
}
return null;
}
public static void printAccessibleTree(PrintWriter log, XAccessible xacc, boolean debugIsActive) {
debug = debugIsActive;
if (debug) printAccessibleTree(log, xacc, "");
}
public static void printAccessibleTree(PrintWriter log, XAccessible xacc) {
printAccessibleTree(log, xacc, "");
}
protected static void printAccessibleTree(PrintWriter log,
XAccessible xacc, String indent) {
XAccessibleContext ac = xacc.getAccessibleContext();
logging(log,indent + ac.getAccessibleRole() + "," +
ac.getAccessibleName() + "(" +
ac.getAccessibleDescription() + "):" +
utils.getImplName(ac));
XAccessibleComponent aComp = (XAccessibleComponent) UnoRuntime.queryInterface(
XAccessibleComponent.class, xacc);
if (aComp != null) {
String bounds = "(" + aComp.getBounds().X + "," +
aComp.getBounds().Y + ")" + " (" +
aComp.getBounds().Width + "," +
aComp.getBounds().Height + ")";
bounds = "The boundary Rectangle is " + bounds;
logging(log,indent + indent + bounds);
}
boolean isShowing = ac.getAccessibleStateSet()
.contains(com.sun.star.accessibility.AccessibleStateType.SHOWING);
logging(log,indent + indent + "StateType contains SHOWING: " +
isShowing);
int k = ac.getAccessibleChildCount();
if (ac.getAccessibleChildCount() > 100) {
k = 50;
}
for (int i = 0; i < k; i++) {
try {
printAccessibleTree(log, ac.getAccessibleChild(i),
indent + " ");
} catch (com.sun.star.lang.IndexOutOfBoundsException e) {
System.out.println("Couldn't get Child");
}
}
if (ac.getAccessibleChildCount() > 100) {
k = ac.getAccessibleChildCount();
int st = ac.getAccessibleChildCount() - 50;
logging(log,indent + " " + " ...... [skipped] ......");
for (int i = st; i < k; i++) {
try {
printAccessibleTree(log, ac.getAccessibleChild(i),
indent + " ");
} catch (com.sun.star.lang.IndexOutOfBoundsException e) {
System.out.println("Couldn't get Child");
}
}
}
}
public static String accessibleToString(Object AC) {
XAccessibleContext xAC = (XAccessibleContext) UnoRuntime.queryInterface(
XAccessibleContext.class, AC);
if (xAC != null) {
return "" + xAC.getAccessibleRole() + "," +
xAC.getAccessibleName() + "(" +
xAC.getAccessibleDescription() + "):";
}
XAccessible xA = (XAccessible) UnoRuntime.queryInterface(
XAccessible.class, AC);
if (xA == null) {
return "(Not supported)";
}
xAC = xA.getAccessibleContext();
return "" + xAC.getAccessibleRole() + "," + xAC.getAccessibleName() +
"(" + xAC.getAccessibleDescription() + ")";
}
public static boolean equals(XAccessible c1, XAccessible c2) {
if ((c1 == null) || (c2 == null)) {
return c1 == c2;
}
return AccessibilityTools.equals(c1.getAccessibleContext(),
c2.getAccessibleContext());
}
public static boolean equals(XAccessibleContext c1, XAccessibleContext c2) {
if ((c1 == null) || (c2 == null)) {
return c1 == c2;
}
if (c1.getAccessibleRole() != c2.getAccessibleRole()) {
return false;
}
if (!c1.getAccessibleName().equals(c2.getAccessibleName())) {
return false;
}
if (!c1.getAccessibleDescription()
.equals(c2.getAccessibleDescription())) {
return false;
}
if (c1.getAccessibleChildCount() != c2.getAccessibleChildCount()) {
return false;
}
return AccessibilityTools.equals(c1.getAccessibleParent(),
c2.getAccessibleParent());
}
private static void logging(PrintWriter log, String content){
if (debug) log.println(content);
}
}
|
package ifc.sdb;
import lib.MultiPropertyTest;
import com.sun.star.beans.PropertyValue;
/**
* Testing <code>com.sun.star.sdb.DataSource</code>
* service properties :
* <ul>
* <li><code> Name</code></li>
* <li><code> URL</code></li>
* <li><code> Info</code></li>
* <li><code> User</code></li>
* <li><code> Password</code></li>
* <li><code> IsPasswordRequired</code></li>
* <li><code> SuppressVersionColumns</code></li>
* <li><code> IsReadOnly</code></li>
* <li><code> NumberFormatsSupplier</code></li>
* <li><code> TableFilter</code></li>
* <li><code> TableTypeFilter</code></li>
* </ul> <p>
* Properties testing is automated by <code>lib.MultiPropertyTest</code> <p>.
* After this interface test <b>it's better to recreate</b> object tested.
* @see com.sun.star.beans.XPropertySet
* @see com.sun.star.beans.XPropertySetInfo
* @see com.sun.star.beans.Property
* @see com.sun.star.lang.XServiceInfo
*/
public class _DataSource extends MultiPropertyTest {
/**
* This property is an array of additional parameters for database
* connecting. Parameter is <code>PropertyValue</code> structure.
* The test just changes existing array onto array with a single
* element <code>("user", "API_QA_Tester")</code> <p>
*
* After testing old value is set for this property. <p>
*
* Result is OK: if property successfully changed with no excepions.
* @see com.sun.star.beans.PropertyValue
*/
public void _Info() {
try {
Object oldInfo = oObj.getPropertyValue("Info") ;
testProperty("Info", new PropertyTester() {
protected Object getNewValue(String propName, Object oldValue) {
PropertyValue propUsr = new PropertyValue(),
propPass = new PropertyValue() ;
propUsr.Name = "user" ;
propUsr.Value = "API_QA_Tester" ;
propPass.Name = "password" ;
propPass.Value = "guest" ;
return new PropertyValue[] { propUsr, propPass } ;
}
}) ;
oObj.setPropertyValue("Info", oldInfo) ;
} catch(com.sun.star.beans.UnknownPropertyException e) {}
catch(com.sun.star.beans.PropertyVetoException e) {}
catch(com.sun.star.lang.IllegalArgumentException e) {}
catch(com.sun.star.lang.WrappedTargetException e) {}
}
/**
* Property is tested by the common method, but after testing
* old value is set for this property.
*/
public void _URL() {
try {
Object oldURL = oObj.getPropertyValue("URL") ;
testProperty("URL") ;
oObj.setPropertyValue("URL", oldURL) ;
} catch(com.sun.star.beans.UnknownPropertyException e) {}
catch(com.sun.star.beans.PropertyVetoException e) {}
catch(com.sun.star.lang.IllegalArgumentException e) {}
catch(com.sun.star.lang.WrappedTargetException e) {}
}
/**
* Property is tested by the common method, but after testing
* old value is set for this property.
*/
public void _User() {
try {
Object oldUser = oObj.getPropertyValue("User") ;
testProperty("User") ;
oObj.setPropertyValue("User", oldUser) ;
} catch(com.sun.star.beans.UnknownPropertyException e) {}
catch(com.sun.star.beans.PropertyVetoException e) {}
catch(com.sun.star.lang.IllegalArgumentException e) {}
catch(com.sun.star.lang.WrappedTargetException e) {}
}
/**
* Property is tested by the common method, but after testing
* old value is set for this property.
*/
public void _Password() {
try {
Object oldPass = oObj.getPropertyValue("Password") ;
testProperty("Password") ;
oObj.setPropertyValue("Password", oldPass) ;
} catch(com.sun.star.beans.UnknownPropertyException e) {}
catch(com.sun.star.beans.PropertyVetoException e) {}
catch(com.sun.star.lang.IllegalArgumentException e) {}
catch(com.sun.star.lang.WrappedTargetException e) {}
}
/**
* New value for the test is always <code>null</code>.
*/
public void _NumberFormatsSupplier() {
testProperty("NumberFormatsSupplier", new PropertyTester() {
protected Object getNewValue(String propName, Object oldValue) {
return null ;
}
}) ;
}
/**
* If object test allows to recreate environment it is better to do it.
*/
public void after() {
try {
oObj.setPropertyValue("IsPasswordRequired",new Boolean(false));
} catch (Exception e) {
log.println("Couldn't set 'IsPasswordRequired' to false");
}
}
} // finish class _DataSource
|
package mod._sc;
import java.io.PrintWriter;
import lib.StatusException;
import lib.TestCase;
import lib.TestEnvironment;
import lib.TestParameters;
import util.SOfficeFactory;
import com.sun.star.awt.Rectangle;
import com.sun.star.container.XIndexAccess;
import com.sun.star.lang.XComponent;
import com.sun.star.lang.XMultiServiceFactory;
import com.sun.star.sheet.XCellRangeAddressable;
import com.sun.star.sheet.XSpreadsheet;
import com.sun.star.sheet.XSpreadsheetDocument;
import com.sun.star.sheet.XSpreadsheets;
import com.sun.star.table.CellRangeAddress;
import com.sun.star.table.XCell;
import com.sun.star.table.XCellRange;
import com.sun.star.table.XTableCharts;
import com.sun.star.table.XTableChartsSupplier;
import com.sun.star.uno.AnyConverter;
import com.sun.star.uno.Type;
import com.sun.star.uno.UnoRuntime;
/**
* Test for object which is represented by service
* <code>com.sun.star.table.TableCharts</code>. <p>
* Object implements the following interfaces :
* <ul>
* <li> <code>com::sun::star::container::XNameAccess</code></li>
* <li> <code>com::sun::star::container::XIndexAccess</code></li>
* <li> <code>com::sun::star::container::XElementAccess</code></li>
* <li> <code>com::sun::star::table::XTableCharts</code></li>
* </ul>
* @see com.sun.star.table.TableCharts
* @see com.sun.star.container.XNameAccess
* @see com.sun.star.container.XIndexAccess
* @see com.sun.star.container.XElementAccess
* @see com.sun.star.table.XTableCharts
* @see ifc.container._XNameAccess
* @see ifc.container._XIndexAccess
* @see ifc.container._XElementAccess
* @see ifc.table._XTableCharts
*/
public class ScChartsObj extends TestCase {
static XSpreadsheetDocument xSheetDoc = null;
/**
* Creates Spreadsheet document.
*/
protected void initialize( TestParameters tParam, PrintWriter log ) {
// get a soffice factory object
SOfficeFactory SOF = SOfficeFactory.getFactory( (XMultiServiceFactory)tParam.getMSF());
try {
log.println( "creating a sheetdocument" );
xSheetDoc = SOF.createCalcDoc(null);;
} catch (com.sun.star.uno.Exception e) {
// Some exception occures.FAILED
e.printStackTrace( log );
throw new StatusException( "Couldn't create document", e );
}
}
/**
* Disposes Spreadsheet document.
*/
protected void cleanup( TestParameters tParam, PrintWriter log ) {
log.println( " disposing xSheetDoc " );
XComponent oComp = (XComponent)
UnoRuntime.queryInterface(XComponent.class, xSheetDoc);
util.DesktopTools.closeDoc(oComp);
}
/**
* Creating a Testenvironment for the interfaces to be tested.
* Retrieves a collection of spreadsheets from a document
* and takes one of them. Inserts some values into the cells of the some cell
* range address. Obtains the collection of the charts using the interface
* <code>XTableChartsSupplier</code>. Creates and adds the chart that using
* the data from the cells of this cell range address. Collection of
* the charts is the instance of the service
* <code>com.sun.star.table.TableCharts</code>.
* Object relations created :
* <ul>
* <li> <code>'RECT'</code> for
* {@link ifc.table._XTableCharts}(of type <code>Rectangle</code>
* the position of the chart)</li>
* <li> <code>'ADDR'</code> for
* {@link ifc.table._XTableCharts}(of type
* <code>com.sun.star.table.CellRangeAddress[]</code> data source ranges
* for chart creating)</li>
* </ul>
* @see com.sun.star.container.XNamed
* @see com.sun.star.table.XTableChartsSupplier
*/
protected synchronized TestEnvironment createTestEnvironment(TestParameters Param, PrintWriter log) {
XSpreadsheet oSheet=null;
try {
log.println("Getting spreadsheet") ;
XSpreadsheets oSheets = xSheetDoc.getSheets() ;
XIndexAccess oIndexSheets = (XIndexAccess)
UnoRuntime.queryInterface(XIndexAccess.class, oSheets);
oSheet = (XSpreadsheet) AnyConverter.toObject(
new Type(XSpreadsheet.class),oIndexSheets.getByIndex(0));
} catch (com.sun.star.lang.WrappedTargetException e) {
log.println("Couldn't get Sheet ");
e.printStackTrace(log);
throw new StatusException("Couldn't get sheet", e);
} catch (com.sun.star.lang.IndexOutOfBoundsException e) {
log.println("Couldn't get Sheet ");
e.printStackTrace(log);
throw new StatusException("Couldn't get sheet", e);
} catch (com.sun.star.lang.IllegalArgumentException e) {
log.println("Couldn't get Sheet ");
e.printStackTrace(log);
throw new StatusException("Couldn't get sheet", e);
}
log.println("Creating the Header") ;
insertIntoCell(1,0,"JAN",oSheet,"");
insertIntoCell(2,0,"FEB",oSheet,"");
insertIntoCell(3,0,"MAR",oSheet,"");
insertIntoCell(4,0,"APR",oSheet,"");
insertIntoCell(5,0,"MAI",oSheet,"");
insertIntoCell(6,0,"JUN",oSheet,"");
insertIntoCell(7,0,"JUL",oSheet,"");
insertIntoCell(8,0,"AUG",oSheet,"");
insertIntoCell(9,0,"SEP",oSheet,"");
insertIntoCell(10,0,"OCT",oSheet,"");
insertIntoCell(11,0,"NOV",oSheet,"");
insertIntoCell(12,0,"DEC",oSheet,"");
insertIntoCell(13,0,"SUM",oSheet,"");
log.println("Fill the lines");
insertIntoCell(0,1,"Smith",oSheet,"");
insertIntoCell(1,1,"42",oSheet,"V");
insertIntoCell(2,1,"58.9",oSheet,"V");
insertIntoCell(3,1,"-66.5",oSheet,"V");
insertIntoCell(4,1,"43.4",oSheet,"V");
insertIntoCell(5,1,"44.5",oSheet,"V");
insertIntoCell(6,1,"45.3",oSheet,"V");
insertIntoCell(7,1,"-67.3",oSheet,"V");
insertIntoCell(8,1,"30.5",oSheet,"V");
insertIntoCell(9,1,"23.2",oSheet,"V");
insertIntoCell(10,1,"-97.3",oSheet,"V");
insertIntoCell(11,1,"22.4",oSheet,"V");
insertIntoCell(12,1,"23.5",oSheet,"V");
insertIntoCell(13,1,"=SUM(B2:M2)",oSheet,"");
insertIntoCell(0,2,"Jones",oSheet,"");
insertIntoCell(1,2,"21",oSheet,"V");
insertIntoCell(2,2,"40.9",oSheet,"V");
insertIntoCell(3,2,"-57.5",oSheet,"V");
insertIntoCell(4,2,"-23.4",oSheet,"V");
insertIntoCell(5,2,"34.5",oSheet,"V");
insertIntoCell(6,2,"59.3",oSheet,"V");
insertIntoCell(7,2,"27.3",oSheet,"V");
insertIntoCell(8,2,"-38.5",oSheet,"V");
insertIntoCell(9,2,"43.2",oSheet,"V");
insertIntoCell(10,2,"57.3",oSheet,"V");
insertIntoCell(11,2,"25.4",oSheet,"V");
insertIntoCell(12,2,"28.5",oSheet,"V");
insertIntoCell(13,2,"=SUM(B3:M3)",oSheet,"");
insertIntoCell(0,3,"Brown",oSheet,"");
insertIntoCell(1,3,"31.45",oSheet,"V");
insertIntoCell(2,3,"-20.9",oSheet,"V");
insertIntoCell(3,3,"-117.5",oSheet,"V");
insertIntoCell(4,3,"23.4",oSheet,"V");
insertIntoCell(5,3,"-114.5",oSheet,"V");
insertIntoCell(6,3,"115.3",oSheet,"V");
insertIntoCell(7,3,"-171.3",oSheet,"V");
insertIntoCell(8,3,"89.5",oSheet,"V");
insertIntoCell(9,3,"41.2",oSheet,"V");
insertIntoCell(10,3,"71.3",oSheet,"V");
insertIntoCell(11,3,"25.4",oSheet,"V");
insertIntoCell(12,3,"38.5",oSheet,"V");
insertIntoCell(13,3,"=SUM(A4:L4)",oSheet,"");
// insert a chart
Rectangle oRect = new Rectangle(500, 3000, 25000, 11000);
XCellRange oRange = (XCellRange)
UnoRuntime.queryInterface(XCellRange.class, oSheet);
XCellRange myRange = oRange.getCellRangeByName("A1:N4");
XCellRangeAddressable oRangeAddr = (XCellRangeAddressable)
UnoRuntime.queryInterface(XCellRangeAddressable.class, myRange);
CellRangeAddress myAddr = oRangeAddr.getRangeAddress();
CellRangeAddress[] oAddr = new CellRangeAddress[1];
oAddr[0] = myAddr;
XTableChartsSupplier oSupp = (XTableChartsSupplier)
UnoRuntime.queryInterface(XTableChartsSupplier.class, oSheet);
log.println("Insert Chart");
XTableCharts oCharts = oSupp.getCharts();
oCharts.addNewByName("ScChartObj", oRect, oAddr, true, true);
log.println("creating a new environment for object");
TestEnvironment tEnv = new TestEnvironment(oCharts);
tEnv.addObjRelation("RECT", oRect);
tEnv.addObjRelation("ADDR", oAddr);
return tEnv;
}
/**
* Inserts a value or a formula in the cell of the spreasheet.
* @param CellX is the column index of the cell
* @param CellY is the row index of the cell
* @param theValue string representation of the value
* @param TT1 specify the spreadsheet, the interface
* <code>com.sun.star.sheet.XSpreadsheet</code>
* @param flag if it's equal to <code>'V'</code> then the method inserts
* a double-value in the cell else it inserts a formula in the cell
*/
public static void insertIntoCell(
int CellX, int CellY, String theValue, XSpreadsheet TT1, String flag) {
XCell oCell = null;
try {
oCell = TT1.getCellByPosition(CellX, CellY);
} catch (com.sun.star.lang.IndexOutOfBoundsException ex) {
System.out.println("Could not get Cell");
}
if (flag.equals("V")) {
oCell.setValue(new Float(theValue).floatValue());
} else {
oCell.setFormula(theValue);
}
} // end of insertIntoCell
}
|
package de.aima13.whoami.modules;
import de.aima13.whoami.Analyzable;
import java.io.*;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.SortedMap;
import org.apache.tika.exception.TikaException;
import org.apache.tika.metadata.Metadata;
import org.apache.tika.parser.ParseContext;
import org.apache.tika.parser.Parser;
import org.apache.tika.parser.mp3.Mp3Parser;
import org.xml.sax.ContentHandler;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
public class Music implements Analyzable {
List<File> localFiles = new ArrayList<File>();
List<File> musicDatabases = new ArrayList<File>();
List<File> browserFiles = new ArrayList<File>();
@Override
//mit diesen Dateitypen kann das Modul arbeiten.
public List<String> getFilter() {
//a) Sammelt bisher nur MP3-Dateien (.FLAC, .RM, .acc, .ogg, .wav?)
List<String> filterMusic = new ArrayList<String>();
filterMusic.add("*.mp3");
filterMusic.add("*.MP3");
//b) Browser-history
filterMusic.add("**Google/Profile/*/history");
filterMusic.add("**Firefox**places.sqlite");
return filterMusic;
//c) windows (registry)?: spotify, wimp, naster... (?)
//-> Keine Daten oder RegDaten?
}
@Override
public void setFileInputs(List<File> files) throws Exception {
if (files != null && !files.isEmpty()) {
musicDatabases = files;
}
else {
throw new IllegalArgumentException("Keine Musikspuren gefunden");
}
//Spalte Dateien in BrowserFiles und lokale Dateien auf
for(File element : musicDatabases){
if(element.getName().contains(".mp3")){
localFiles.add(element);
}
else {
browserFiles.add(element);
}
}
}
}
@Override
public String getHtml() {
return null;
}
@Override
public SortedMap<String, String> getCsvContent() {
return null;
}
@Override
//Steuerung der Analyse der Musik
public void run() {
}
public void scoreUser(){
}
public void readId3Tag() {
/**
* @param
*/
//String fileLocation = "G:/asas/album/song.mp3"
for(File file : localFiles) {
try {
String fileLocation = file.getCanonicalPath();
InputStream input = new FileInputStream(new File(fileLocation));
ContentHandler handler = new DefaultHandler();
Metadata metadata = new Metadata();
Parser parser = new Mp3Parser();
ParseContext parseCtx = new ParseContext();
parser.parse(input, handler, metadata, parseCtx);
input.close();
// List all metadata
String[] metadataNames = metadata.names();
for (String name : metadataNames) {
System.out.println(name + ": " + metadata.get(name));
}
// Retrieve the necessary info from metadata
// Names - title, xmpDM:artist etc. - mentioned below may differ based
System.out.println("
System.out.println("Title: " + metadata.get("title"));
System.out.println("Artists: " + metadata.get("xmpDM:artist"));
System.out.println("Composer : " + metadata.get("xmpDM:composer"));
System.out.println("Genre : " + metadata.get("xmpDM:genre"));
System.out.println("Album : " + metadata.get("xmpDM:album"));
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (SAXException e) {
e.printStackTrace();
} catch (TikaException e) {
e.printStackTrace();
}
}
}
}
public void checkNativeClients() {
try
{
Process p=Runtime.getRuntime().exec("wmic product get name");
p.waitFor();
BufferedReader reader=new BufferedReader(
new InputStreamReader(p.getInputStream())
);
String line;
while((line = reader.readLine()) != null)
{
System.out.println(line);
}
}
catch(IOException e1) {}
catch(InterruptedException e2) {}
System.out.println("Done");
}
public void readBrowser(){
}
}
|
package weave.servlets;
import java.io.File;
import java.rmi.RemoteException;
import java.util.UUID;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import weave.beans.KMeansClusteringResult;
import weave.beans.HierarchicalClusteringResult;
import weave.beans.LinearRegressionResult;
import weave.beans.RResult;
import weave.config.WeaveContextParams;
import weave.servlets.GenericServlet;
import weave.utils.ListUtils;
import org.rosuda.REngine.REXP;
import org.rosuda.REngine.REXPInteger;
import org.rosuda.REngine.REXPString;
import org.rosuda.REngine.REXPDouble;
import org.rosuda.REngine.REXPMismatchException;
import org.rosuda.REngine.Rserve.RConnection;
import org.rosuda.REngine.Rserve.RserveException;
public class RService extends GenericServlet
{
private static final long serialVersionUID = 1L;
public RService()
{
}
public void init(ServletConfig config) throws ServletException
{
super.init(config);
docrootPath = WeaveContextParams.getInstance(config.getServletContext()).getDocrootPath();
}
private String docrootPath = "";
private String rFolderName = "R_output";
private String plotEvalScript(RConnection rConnection, String script, boolean showWarnings) throws REXPMismatchException,RserveException
{
String file = String.format("user_script_%s.jpg", UUID.randomUUID());
String dir = docrootPath + rFolderName + "/";
(new File(dir)).mkdirs();
String str = String.format("jpeg(\"%s\")", dir + file);
evalScript(rConnection, str, showWarnings);
rConnection.eval(script);
rConnection.eval("dev.off()");
return rFolderName + "/" + file;
}
private REXP evalScript(RConnection rConnection, String script, boolean showWarnings) throws REXPMismatchException,RserveException
{
// rConnection.voidEval("");
REXP evalValue = null;
if(showWarnings)
evalValue = rConnection.eval("try({ options(warn=2) \n" + script + "},silent=TRUE)");
else
evalValue = rConnection.eval("try({ options(warn=1) \n" + script + "},silent=TRUE)");
return evalValue;
}
private RConnection getRConnection() throws RemoteException
{
RConnection rConnection = null; // establishing R connection
try
{
rConnection = new RConnection();
// rConnection.eval(readFile("Rscripts/MRegress.R"));
}
catch (RserveException e)
{
e.printStackTrace();
throw new RemoteException("Unable to connect to RServe");
}
return rConnection;
}
public RResult[] runScript(String[] inputNames, Object[][] inputValues, String[] outputNames, String script, String plotScript, boolean showIntermediateResults, boolean showWarnings) throws Exception
{
RConnection rConnection = getRConnection();
//System.out.println(keys.length);
String output = "";
RResult[] results = null;
REXP evalValue;
try
{
// ASSIGNS inputNames to respective Vector in R "like x<-c(1,2,3,4)"
for (int i = 0; i < inputNames.length; i++)
{
String name = inputNames[i];
if (inputValues[i][0] instanceof String)
{
String[] value = ListUtils.copyStringArray(inputValues[i], new String[inputValues[i].length]);
rConnection.assign(name, value);
}
else
{
double[] value = ListUtils.copyDoubleArray(inputValues[i], new double[inputValues[i].length]);
rConnection.assign(name, value);
}
// double[] value = inputValues[i];
// System.out.println("input " + name);
// Assigning Column to its Name in R
}
// R Script to EVALUATE inputTA(from R Script Input TextArea)
if (showIntermediateResults)
{
String[] rScript = script.split("\n");
for (int i = 0; i < rScript.length; i++)
{
REXP individualEvalValue = evalScript(rConnection, rScript[i], showWarnings);
// to-do remove debug information from string
String trimedString = individualEvalValue.toString();
while (trimedString.indexOf('[') > 0)
{
int pos = trimedString.indexOf('[');
// System.out.println(pos + "\n");
// System.out.println(trimedString + "\n");
trimedString = trimedString.substring(pos + 1);
}
trimedString = "[" + trimedString;
output = output.concat(trimedString);
output += "\n";
}
}
else
{
REXP completeEvalValue = evalScript(rConnection, script, showWarnings);
output = completeEvalValue.toString();
}
// R Script to EVALUATE outputTA(from R Script Output TextArea)
if (showIntermediateResults)
{
int i;
int iterationTimes;
if (plotScript != "")
{
results = new RResult[outputNames.length + 2];
String plotEvalValue = plotEvalScript(rConnection, plotScript, showWarnings);
results[0] = new RResult("Plot Results", plotEvalValue);
results[1] = new RResult("Intermediate Results", output);
i = 2;
iterationTimes = outputNames.length + 2;
}
else
{
results = new RResult[outputNames.length + 1];
results[0] = new RResult("Intermediate Results", output);
i = 1;
iterationTimes = outputNames.length + 1;
}
// to add intermediate results extra object is created as first
// input, so results length will be one greater than OutputNames
// int i =1;
// int iterationTimes =outputNames.length;
for (; i < iterationTimes; i++)
{
String name;
// Boolean addedTolist = false;
if (iterationTimes == outputNames.length + 2){
name = outputNames[i - 2];
}
else{
name = outputNames[i - 1];
}
// Script to get R - output
evalValue = evalScript(rConnection, name, showWarnings);
if (evalValue.isVector()){
if (evalValue instanceof REXPString)
results[i] = new RResult(name, evalValue.asStrings());
else if (evalValue instanceof REXPInteger)
results[i] = new RResult(name, evalValue.asIntegers());
else if (evalValue instanceof REXPDouble){
if (evalValue.dim() == null)
results[i] = new RResult(name, evalValue.asDoubles());
else
results[i] = new RResult(name, evalValue.asDoubleMatrix());
}
else{
// if no previous cases were true, return debug String
results[i] = new RResult(name, evalValue.toDebugString());
}
}
else{
results[i] = new RResult(name, evalValue.toDebugString());
}
// System.out.println(name + " = " + evalValue.toDebugString() + "\n");
}//end of for - to store result
}//end of IF for intermediate results
else
{
int i;
int iterationTimes;
if (plotScript != "")
{
results = new RResult[outputNames.length + 1];
String plotEvalValue = plotEvalScript(rConnection, plotScript, showWarnings);
// System.out.println(plotEvalValue);
results[0] = new RResult("Plot Results", plotEvalValue);
i = 1;
iterationTimes = outputNames.length + 1;
}
else
{
results = new RResult[outputNames.length];
i = 0;
iterationTimes = outputNames.length;
}
// to outputNames script result
// results = new RResult[outputNames.length];
for (; i < iterationTimes; i++)
{
String name;
// Boolean addedTolist = false;
if (iterationTimes == outputNames.length + 1){
name = outputNames[i - 1];
}
else{
name = outputNames[i];
}
// Script to get R - output
evalValue = evalScript(rConnection, name, showWarnings);
// System.out.println(evalValue);
if (evalValue.isVector()){
if (evalValue instanceof REXPString)
results[i] = new RResult(name, evalValue.asStrings());
else if (evalValue instanceof REXPInteger)
results[i] = new RResult(name, evalValue.asIntegers());
else if (evalValue instanceof REXPDouble){
if (evalValue.dim() == null)
results[i] = new RResult(name, evalValue.asDoubles());
else
results[i] = new RResult(name, evalValue.asDoubleMatrix());
}
else{
// if no previous cases were true, return debug String
results[i] = new RResult(name, evalValue.toDebugString());
}
}
else{
results[i] = new RResult(name, evalValue.toDebugString());
}
// System.out.println(name + " = " + evalValue.toDebugString() + "\n");
}
}
}
catch (Exception e) {
e.printStackTrace();
output += e.getMessage();
// to send error from R to As3 side results is created with one
// object
results = new RResult[1];
results[0] = new RResult("Error Statement", output);
}
finally
{
rConnection.close();
}
return results;
}
public LinearRegressionResult linearRegression(double[] dataX, double[] dataY) throws RemoteException
{
if (dataX.length == 0 || dataY.length == 0)
throw new RemoteException("Unable to run computation on zero-length arrays.");
if (dataX.length != dataY.length)
throw new RemoteException("Unable to run computation on two arrays with different lengths (" + dataX.length
+ " != " + dataY.length + ").");
// System.out.println("entering linearRegression()");
RConnection rConnection = getRConnection();
// System.out.println("got r connection");
LinearRegressionResult result = new LinearRegressionResult();
try
{
// Push the data to R
rConnection.assign("x", dataX);
rConnection.assign("y", dataY);
// Perform the calculation
rConnection.eval("fit <- lm(y~x)");
// option to draw the plot, regression line and store the image
rConnection.eval(String.format("jpeg(\"%s\")", docrootPath + rFolderName + "/Linear_Regression.jpg"));
rConnection.eval("plot(x,y)");
rConnection.eval("abline(fit)");
rConnection.eval("dev.off()");
// Get the data from R
result.setIntercept(rConnection.eval("coefficients(fit)[1]").asDouble());
result.setSlope(rConnection.eval("coefficients(fit)[2]").asDouble());
result.setRSquared(rConnection.eval("summary(fit)$r.squared").asDouble());
result.setSummary("");// rConnection.eval("summary(fit)").asString());
result.setResidual(rConnection.eval("resid(fit)").asDoubles());
}
catch (Exception e)
{
e.printStackTrace();
throw new RemoteException(e.getMessage());
}
finally
{
rConnection.close();
}
return result;
}
public KMeansClusteringResult kMeansClustering(double[] dataX, double[] dataY, int numberOfClusters) throws RemoteException
{
int[] clusterNumber = new int[1];
clusterNumber[0] = numberOfClusters;
int[] iterations = new int[1];
iterations[0] = 2;
if (dataX.length == 0 || dataY.length == 0)
throw new RemoteException("Unable to run computation on zero-length arrays.");
if (dataX.length != dataY.length)
throw new RemoteException("Unable to run computation on two arrays with different lengths (" + dataX.length
+ " != " + dataY.length + ").");
RConnection rConnection = getRConnection();
KMeansClusteringResult kclresult = new KMeansClusteringResult();
try
{
// Push the data to R
rConnection.assign("x", dataX);
rConnection.assign("y", dataY);
rConnection.assign("clusternumber", clusterNumber);
rConnection.assign("iter.max", iterations);
// Performing the calculation
rConnection.eval("dataframe1 <- data.frame(x,y)");
// Each run of the algorithm gives a different result, thus continue
// till results are constant
rConnection
.eval("Clustering <- function(clusternumber, iter.max)\n{result1 <- kmeans(dataframe1, clusternumber, iter.max)\n result2 <- kmeans(dataframe1, clusternumber, (iter.max-1))\n while(result1$centers != result2$centers){ iter.max <- iter.max + 1 \n result1 <- kmeans(dataframe1, clusternumber, iter.max) \n result2 <- kmeans(dataframe1, clusternumber, (iter.max-1))} \n print(result1) \n print(result2)}");
rConnection.eval("Cluster <- Clustering(clusternumber, iter.max)");
// option for drawing a graph, shows centroids
// Get the data from R
// Returns a vector indicating which cluster each data point belongs
kclresult.setClusterGroup(rConnection.eval("Cluster$cluster").asDoubles());
// Returns the means of each of the clusters
kclresult.setClusterMeans(rConnection.eval("Cluster$centers").asDoubleMatrix());
// Returns the size of each cluster
kclresult.setClusterSize(rConnection.eval("Cluster$size").asDoubles());
// Returns the sum of squares within each cluster
kclresult.setWithinSumOfSquares(rConnection.eval("Cluster$withinss").asDoubles());
// Returns the image from R
// option for storing the image of the graphic output from R
String str = String.format("jpeg(\"%s\")", docrootPath + rFolderName + "/Kmeans_Clustering.jpg");
// System.out.println(str);
evalScript(rConnection, str,false);
rConnection
.eval("plot(dataframe1,xlab= \"x\", ylab= \"y\", main = \"Kmeans Clustering\", col = Cluster$cluster) \n points(Cluster$centers, col = 1:5, pch = 10)");
rConnection.eval("dev.off()");
kclresult.setRImageFilePath("Kmeans_Clustering.jpg");
}
catch (Exception e)
{
e.printStackTrace();
throw new RemoteException(e.getMessage());
}
finally
{
rConnection.close();
}
return kclresult;
}
public HierarchicalClusteringResult hierarchicalClustering(double[] dataX, double[] dataY) throws RemoteException
{
String[] agglomerationMethod = new String[7];
agglomerationMethod[0] = "ward";
agglomerationMethod[1] = "average";
agglomerationMethod[2] = "centroid";
agglomerationMethod[3] = "single";
agglomerationMethod[4] = "complete";
agglomerationMethod[5] = "median";
agglomerationMethod[6] = "mcquitty";
String agglomerationMethodType = new String("ward");
if (dataX.length == 0 || dataY.length == 0)
throw new RemoteException("Unable to run computation on zero-length arrays.");
if (dataX.length != dataY.length)
throw new RemoteException("Unable to run computation on two arrays with different lengths (" + dataX.length
+ " != " + dataY.length + ").");
RConnection rConnection = getRConnection();
HierarchicalClusteringResult hclresult = new HierarchicalClusteringResult();
try
{
// Push the data to R
rConnection.assign("x", dataX);
rConnection.assign("y", dataY);
// checking for user method match
for (int j = 0; j < agglomerationMethod.length; j++)
{
if (agglomerationMethod[j].equals(agglomerationMethodType))
{
rConnection.assign("method", agglomerationMethod[j]);
}
}
// Performing the calculations
rConnection.eval("dataframe1 <- data.frame(x,y)");
rConnection.eval("HCluster <- hclust(d = dist(dataframe1), method)");
// option for drawing the hierarchical tree and storing the image
rConnection.eval(String.format("jpeg(\"%s\")", docrootPath + rFolderName + "/Hierarchical_Clustering.jpg"));
rConnection.eval("plot(HCluster, main = \"Hierarchical Clustering\")");
rConnection.eval("dev.off()");
// Get the data from R
hclresult.setClusterSequence(rConnection.eval("HCluster$merge").asDoubleMatrix());
hclresult.setClusterMethod(rConnection.eval("HCluster$method").asStrings());
// hclresult.setClusterLabels(rConnection.eval("HCluster$labels").asStrings());
hclresult.setClusterDistanceMeasure(rConnection.eval("HCluster$dist.method").asStrings());
}
catch (Exception e)
{
e.printStackTrace();
throw new RemoteException(e.getMessage());
}
finally
{
rConnection.close();
}
return hclresult;
}
}
|
package bamboo.crawl;
import bamboo.app.Bamboo;
import bamboo.core.Streams;
import bamboo.task.*;
import bamboo.util.SurtFilter;
import com.google.common.annotations.VisibleForTesting;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonSyntaxException;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonWriter;
import org.apache.commons.io.output.TeeOutputStream;
import org.archive.io.ArchiveReader;
import org.archive.io.ArchiveRecord;
import org.archive.url.SURT;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.nio.channels.Channels;
import java.nio.channels.SeekableByteChannel;
import java.nio.file.*;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;
import static java.nio.charset.StandardCharsets.US_ASCII;
import static java.nio.charset.StandardCharsets.UTF_8;
import static java.nio.file.StandardOpenOption.*;
@Controller
public class WarcsController {
private static final Logger log = LoggerFactory.getLogger(WarcsController.class);
final Bamboo wa;
private TextCache textCache;
public WarcsController(Bamboo wa) {
this.wa = wa;
String textCachePath = System.getenv("WARC_TEXT_CACHE");
if (textCachePath != null) {
Path root = Paths.get(textCachePath);
if (!Files.exists(root)) {
throw new RuntimeException("WARC_TEXT_CACHE not found: " + textCachePath);
}
textCache = new TextCache(root, wa.warcs, wa.textExtractor);
}
}
static class Range {
static final Pattern BYTES_SPEC_PATTERN = Pattern.compile("([0-9]+)?-([0-9]+)?");
final long start, length, total;
public Range(long start, long length, long total) {
this.start = start;
this.length = length;
this.total = total;
}
public String toString() {
return String.format("%d-%d/%d", start, start + length - 1, total);
}
static List<Range> parseHeader(String headerValue, long fileSize) {
if (headerValue == null || !headerValue.startsWith("bytes=") || headerValue.equals("bytes=")) {
return null;
}
List<Range> ranges = new ArrayList<>();
String[] specs = headerValue.substring("bytes=".length()).split(",");
for (String spec: specs) {
Range range = parseByteRange(spec, fileSize);
if (range == null) { // whole file
return null;
}
ranges.add(range);
}
return ranges;
}
static Range parseByteRange(String spec, long fileSize) {
Matcher m = BYTES_SPEC_PATTERN.matcher(spec);
if (m.matches()) {
String startText = m.group(1);
String endText = m.group(2);
if (startText != null) {
long start = Long.parseLong(startText);
long end = endText == null ? fileSize : Long.parseLong(endText);
return new Range(start, end - start + 1, fileSize);
} else if (endText != null) {
long tail = Long.parseLong(endText);
if (tail >= fileSize) {
return null;
}
return new Range(fileSize - tail, tail, fileSize);
}
}
throw new NumberFormatException("Bad byte range: " + spec);
}
}
Warc findWarc(String id) {
try {
long warcId = Long.parseLong(id);
return wa.warcs.get(warcId);
} catch (NumberFormatException e) {
return wa.warcs.getByFilename(id);
}
}
@GetMapping("/warcs/{id}")
public void serve(@PathVariable("id") String id,
@RequestHeader(value = "Range", required = false) String rangeHeader,
HttpServletRequest request, HttpServletResponse response) {
Warc warc = findWarc(id);
List<Range> ranges = Range.parseHeader(rangeHeader, warc.getSize());
try {
if (ranges == null || ranges.isEmpty()) {
response.setContentType("application/warc");
response.setHeader("Content-Length", Long.toString(warc.getSize()));
response.setHeader("Content-Disposition", "filename=" + warc.getFilename());
response.setHeader("Accept-Ranges", "bytes");
try (InputStream src = wa.warcs.openStream(warc);
OutputStream dst = response.getOutputStream()) {
Streams.copy(src, dst);
}
} else if (ranges.size() == 1) {
singleRangeResponse(response, warc, ranges.get(0));
} else {
multipleRangeResponse(response, warc, ranges);
}
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}
private void singleRangeResponse(HttpServletResponse response, Warc warc, Range range) throws IOException {
response.setStatus(206);
response.setContentType("application/warc");
response.setHeader("Content-Range", range.toString());
response.setHeader("Content-Length", Long.toString(range.length));
try (OutputStream out = response.getOutputStream();
SeekableByteChannel in = wa.warcs.openChannel(warc)) {
in.position(range.start);
Streams.copy(Channels.newInputStream(in), out, range.length);
}
}
private static final String boundary = "Te2akaimeeThe8eip5oh";
private void multipleRangeResponse(HttpServletResponse response, Warc warc, List<Range> ranges) throws IOException {
response.setStatus(206);
response.setContentType("multipart/byteranges; boundary=" + boundary);
try (OutputStream out = response.getOutputStream();
SeekableByteChannel in = wa.warcs.openChannel(warc);
InputStream ins = Channels.newInputStream(in)) {
for (Range range : ranges) {
out.write(("--" + boundary + "\r\nContent-Type: application/warc\r\nContent-Range: " + range.toString() + "\r\n\r\n").getBytes(US_ASCII));
in.position(range.start);
Streams.copy(ins, out, range.length);
out.write("\r\n".getBytes(US_ASCII));
}
out.write(("--" + boundary + "--\r\n").getBytes(US_ASCII));
}
}
@GetMapping(value = "/warcs/{id}/cdx")
public void showCdx(@PathVariable("id") String id, HttpServletResponse response) {
Warc warc = findWarc(id);
response.setContentType("text/plain");
try (Writer out = new BufferedWriter(new OutputStreamWriter(response.getOutputStream(), UTF_8));
ArchiveReader reader = wa.warcs.openReader(warc)) {
Cdx.writeCdx(reader, warc.getFilename(), warc.getSize(), out);
out.flush();
} catch (Exception e) {
log.error("Unable to produce CDX for warc " + warc.getId(), e);
}
}
@VisibleForTesting
static final Gson gson;
static {
GsonBuilder builder = new GsonBuilder().setDateFormat("yyyy-MM-dd'T'HH:mm:ssXXX");
String indent = System.getProperty("disableJsonIndent");
if (indent != null && "true".equals(indent)) {
gson = builder.create();
} else {
gson = builder.setPrettyPrinting().create();
}
}
static class CollectionMatcher {
private final SurtFilter filter;
final CollectionInfo info;
public CollectionMatcher(CollectionWithFilters collectionWithFilters) {
this.info = new CollectionInfo();
info.setId(collectionWithFilters.getId());
info.setName(collectionWithFilters.getName());
this.filter = new SurtFilter(collectionWithFilters.urlFilters);
}
public boolean matches(String surt) {
return this.filter.accepts(surt);
}
}
private boolean serveTextFromCache(HttpServletRequest request, HttpServletResponse response, Warc warc, List<CollectionMatcher> collections) throws IOException {
if (textCache == null) return false;
Path file = textCache.find(warc.getId());
if (file == null) return false;
response.setContentType("application/json");
try (JsonWriter writer = gson.newJsonWriter(new OutputStreamWriter(response.getOutputStream(), UTF_8));
JsonReader reader = gson.newJsonReader(new InputStreamReader(new GZIPInputStream(Files.newInputStream(file), 8192), UTF_8))) {
reader.beginArray();
writer.beginArray();
while (reader.hasNext()) {
Document doc = gson.fromJson(reader, Document.class);
populateCollectionInfo(collections, doc);
gson.toJson(doc, Document.class, writer);
}
reader.endArray();
writer.endArray();
writer.flush();
return true;
} catch (JsonSyntaxException e) {
log.error("Deleting corrupt cache entry {}", file);
Files.deleteIfExists(file);
// we can't meaningfully recover in this situation so bail and hope the client retries
throw e;
}
}
@GetMapping(value = "/warcs/{id}/text", produces = "application/json")
public void showText(@PathVariable String id, HttpServletRequest request, HttpServletResponse response) throws IOException {
Warc warc = findWarc(id);
Crawl crawl = wa.crawls.get(warc.getCrawlId());
List<CollectionMatcher> collections = wa.collections.findByCrawlSeriesId(crawl.getCrawlSeriesId())
.stream().map(CollectionMatcher::new).collect(Collectors.toList());
if (serveTextFromCache(request, response, warc, collections)) {
return;
}
response.setContentType("application/json");
OutputStream out = response.getOutputStream();
Path cachePath = null;
Path tmpCachePath = null;
OutputStream cacheStream = null;
if (textCache != null) {
cachePath = textCache.entryPath(warc.getId());
tmpCachePath = Paths.get(cachePath.toString() + ".tmp");
cacheStream = new GZIPOutputStream(Files.newOutputStream(tmpCachePath, WRITE, CREATE, TRUNCATE_EXISTING), 8192);
out = new TeeOutputStream(out, cacheStream);
}
OutputStreamWriter streamWriter = new OutputStreamWriter(out, UTF_8);
String url = null;
try (ArchiveReader reader = wa.warcs.openReader(warc)) {
JsonWriter writer = gson.newJsonWriter(streamWriter);
writer.beginArray();
for (ArchiveRecord record : reader) {
url = record.getHeader().getUrl();
if (url == null) continue;
try {
Document doc = wa.textExtractor.extract(record);
populateCollectionInfo(collections, doc);
gson.toJson(doc, Document.class, writer);
} catch (TextExtractionException e) {
continue; // skip it
}
}
writer.endArray();
writer.flush();
if (tmpCachePath != null) {
cacheStream.close();
cacheStream = null;
Files.move(tmpCachePath, cachePath, StandardCopyOption.REPLACE_EXISTING);
}
} catch (Exception | StackOverflowError e) {
String message = "Text extraction failed. warcId=" + warc.getId() + " path=" + warc.getPath() + " recordUrl=" + url;
log.error(message, e);
streamWriter.write("\n\n" + message + "\n");
e.printStackTrace(new PrintWriter(streamWriter));
} finally {
streamWriter.close(); // ensure output stream always closed to avoid gzip issues
if (cacheStream != null) cacheStream.close();
if (tmpCachePath != null) Files.deleteIfExists(tmpCachePath);
}
}
private void populateCollectionInfo(List<CollectionMatcher> collections, Document doc) {
// add collections info
String surt = SURT.toSURT(doc.getUrl());
List<CollectionInfo> docCollections = new ArrayList<>();
for (CollectionMatcher matcher: collections) {
if (matcher.matches(surt)) {
docCollections.add(matcher.info);
}
}
doc.setCollections(docCollections);
}
@GetMapping(value = "/warcs/{id}/details")
String details(@PathVariable String id, Model model) {
Warc warc = findWarc(id);
model.addAttribute("warc", warc);
model.addAttribute("crawl", wa.crawls.get(warc.getCrawlId()));
model.addAttribute("state", wa.warcs.stateName(warc.getStateId()));
return "warc";
}
@PostMapping(value = "/warcs/{id}/reindex", produces = "text/plain")
@ResponseBody
private String reindex(@PathVariable String id) throws IOException {
Warc warc = findWarc(id);
RecordStats stats = wa.cdxIndexer.indexWarc(warc);
return "CDX indexed " + stats.getRecords() + " records";
}
}
|
package org.opennms.netmgt.provision.persist;
import java.util.Set;
import java.util.TreeSet;
import javax.servlet.http.HttpServletRequest;
import org.apache.log4j.Category;
import org.opennms.core.utils.ThreadCategory;
import org.opennms.netmgt.EventConstants;
import org.opennms.netmgt.config.SnmpEventInfo;
import org.opennms.netmgt.config.SnmpPeerFactory;
import org.opennms.netmgt.dao.CategoryDao;
import org.opennms.netmgt.dao.DistPollerDao;
import org.opennms.netmgt.dao.NodeDao;
import org.opennms.netmgt.dao.ServiceTypeDao;
import org.opennms.netmgt.model.OnmsAssetRecord;
import org.opennms.netmgt.model.OnmsDistPoller;
import org.opennms.netmgt.model.OnmsIpInterface;
import org.opennms.netmgt.model.OnmsMonitoredService;
import org.opennms.netmgt.model.OnmsNode;
import org.opennms.netmgt.model.OnmsServiceType;
import org.opennms.netmgt.model.OnmsIpInterface.PrimaryType;
import org.opennms.netmgt.model.events.EventProxy;
import org.opennms.netmgt.model.events.EventProxyException;
import org.opennms.netmgt.provision.persist.requisition.Requisition;
import org.opennms.netmgt.provision.persist.requisition.RequisitionAsset;
import org.opennms.netmgt.provision.persist.requisition.RequisitionCategory;
import org.opennms.netmgt.provision.persist.requisition.RequisitionInterface;
import org.opennms.netmgt.provision.persist.requisition.RequisitionMonitoredService;
import org.opennms.netmgt.provision.persist.requisition.RequisitionNode;
import org.opennms.netmgt.xml.event.Event;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.servlet.ModelAndView;
public class DefaultNodeProvisionService implements NodeProvisionService {
private EventProxy m_eventProxy;
private CategoryDao m_categoryDao;
private NodeDao m_nodeDao;
@Autowired
private DistPollerDao m_distPollerDao;
private ServiceTypeDao m_serviceTypeDao;
private ForeignSourceRepository m_foreignSourceRepository;
private SnmpPeerFactory m_snmpPeerFactory;
public ModelAndView getModelAndView(HttpServletRequest request) {
ModelAndView modelAndView = new ModelAndView();
modelAndView.addObject("foreignSources", m_foreignSourceRepository.getForeignSources());
modelAndView.addObject("requisitions", m_foreignSourceRepository.getRequisitions());
modelAndView.addObject("categories", m_categoryDao.getAllCategoryNames());
modelAndView.addObject("success", Boolean.parseBoolean(request.getParameter("success")));
modelAndView.addObject("foreignSource", request.getParameter("foreignSource"));
return modelAndView;
}
@Transactional
public boolean provisionNode(String foreignSource, String foreignId, String nodeLabel, String ipAddress,
String[] categories, String snmpCommunity, String snmpVersion,
String deviceUsername, String devicePassword, String enablePassword,
String accessMethod, String autoEnable) throws NodeProvisionException {
if (log().isDebugEnabled()) {
log().debug(String.format("adding SNMP community %s (%s)", snmpCommunity, snmpVersion));
}
// Set the SNMP community name (if necessary)
if (snmpCommunity != null && snmpVersion != null) {
try {
SnmpEventInfo info = new SnmpEventInfo();
info.setCommunityString(snmpCommunity);
info.setFirstIPAddress(ipAddress);
info.setVersion(snmpVersion);
m_snmpPeerFactory.define(info);
SnmpPeerFactory.saveCurrent();
} catch (Exception e) {
throw new NodeProvisionException("unable to add SNMP community information", e);
}
}
log().debug("creating requisition node");
// Create a requisition node based on the form input
RequisitionInterface reqIface = new RequisitionInterface();
reqIface.setIpAddr(ipAddress);
reqIface.setManaged(true);
reqIface.setSnmpPrimary("P");
reqIface.setStatus(1);
reqIface.putMonitoredService(new RequisitionMonitoredService("ICMP"));
reqIface.putMonitoredService(new RequisitionMonitoredService("SNMP"));
RequisitionNode reqNode = new RequisitionNode();
reqNode.setNodeLabel(nodeLabel);
reqNode.setForeignId(foreignId);
reqNode.putInterface(reqIface);
for (String category : categories) {
reqNode.putCategory(new RequisitionCategory(category));
}
if (deviceUsername != null) {
reqNode.putAsset(new RequisitionAsset("username", deviceUsername));
}
if (devicePassword != null) {
reqNode.putAsset(new RequisitionAsset("password", devicePassword));
}
if (enablePassword != null) {
reqNode.putAsset(new RequisitionAsset("enable", enablePassword));
}
if (accessMethod != null) {
reqNode.putAsset(new RequisitionAsset("connection", accessMethod));
}
if (autoEnable != null) {
reqNode.putAsset(new RequisitionAsset("autoenable", autoEnable));
}
// Now save it to the requisition
try {
Requisition req = m_foreignSourceRepository.getRequisition(foreignSource);
req.putNode(reqNode);
log().debug("saving requisition node");
m_foreignSourceRepository.save(req);
} catch (ForeignSourceRepositoryException e) {
throw new RuntimeException("unable to retrieve foreign source '" + foreignSource + "'", e);
}
log().debug("creating database node");
// Create the basic node
OnmsDistPoller dp = m_distPollerDao.get("localhost");
OnmsNode node = new OnmsNode();
node.setDistPoller(dp);
node.setType("A");
node.setForeignSource(foreignSource);
node.setForeignId(foreignId);
node.setLabel(nodeLabel);
OnmsIpInterface iface = new OnmsIpInterface();
iface.setNode(node);
iface.setIpAddress(ipAddress);
iface.setIsManaged("M");
iface.setIsSnmpPrimary(new PrimaryType('P'));
node.addIpInterface(iface);
Set<OnmsMonitoredService> services = new TreeSet<OnmsMonitoredService>();
services.add(new OnmsMonitoredService(iface, getServiceType("ICMP")));
services.add(new OnmsMonitoredService(iface, getServiceType("SNMP")));
iface.setMonitoredServices(services);
OnmsAssetRecord asset = new OnmsAssetRecord();
asset.setAutoenable(autoEnable);
asset.setConnection(accessMethod);
asset.setEnable(enablePassword);
asset.setUsername(deviceUsername);
asset.setPassword(devicePassword);
node.setAssetRecord(asset);
log().debug("saving database node");
m_nodeDao.save(node);
node = m_nodeDao.findByForeignId(foreignSource, foreignId);
try {
log().debug("sending event for new node ID " + node.getNodeId());
Event e = new Event();
e.setUei(EventConstants.NODE_ADDED_EVENT_UEI);
e.setNodeid(node.getId());
e.setSource(getClass().getName());
e.setTime(EventConstants.formatToString(new java.util.Date()));
m_eventProxy.send(e);
e = new Event();
e.setUei(EventConstants.NODE_GAINED_INTERFACE_EVENT_UEI);
e.setNodeid(node.getId());
e.setInterface(ipAddress);
e.setSource(getClass().getName());
e.setTime(EventConstants.formatToString(new java.util.Date()));
m_eventProxy.send(e);
e = new Event();
e.setUei(EventConstants.NODE_GAINED_SERVICE_EVENT_UEI);
e.setNodeid(node.getId());
e.setInterface(ipAddress);
e.setService("ICMP");
e.setService("SNMP");
e.setSource(getClass().getName());
e.setTime(EventConstants.formatToString(new java.util.Date()));
m_eventProxy.send(e);
} catch (EventProxyException ex) {
throw new NodeProvisionException("Unable to send node events", ex);
}
return true;
}
private OnmsServiceType getServiceType(String string) {
return m_serviceTypeDao.findByName(string);
}
public void setForeignSourceRepository(ForeignSourceRepository repository) {
m_foreignSourceRepository = repository;
}
public void setCategoryDao(CategoryDao dao) {
m_categoryDao = dao;
}
public void setSnmpPeerFactory(SnmpPeerFactory pf) {
m_snmpPeerFactory = pf;
}
public void setNodeDao(NodeDao dao) {
m_nodeDao = dao;
}
public void setServiceTypeDao(ServiceTypeDao dao) {
m_serviceTypeDao = dao;
}
public void setEventProxy(EventProxy proxy) {
m_eventProxy = proxy;
}
protected Category log() {
return ThreadCategory.getInstance(getClass());
}
}
|
package org.openwms.core.integration.jpa;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.openwms.core.domain.system.usermanagement.Role;
import org.openwms.core.domain.system.usermanagement.SystemUser;
import org.openwms.core.domain.system.usermanagement.User;
import org.openwms.core.domain.system.usermanagement.UserPassword;
import org.openwms.core.integration.UserDao;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
/**
* An UserDaoImpl is an extension of a {@link AbstractGenericJpaDao} about
* functionality regarding {@link User}s. The stereotype annotation
* {@link Repository} marks this class as DAO in the architecture and enables
* exception translation and component scanning. It can be injected by name
* {@value #COMPONENT_NAME}.
* <p>
* All methods have to be invoked within an active transaction context.
* </p>
*
* @author <a href="mailto:scherrer@openwms.org">Heiko Scherrer</a>
* @version $Revision$
* @since 0.1
* @see org.openwms.core.integration.jpa.AbstractGenericJpaDao
* @see org.openwms.core.integration.UserDao
*/
@Transactional(propagation = Propagation.MANDATORY)
@Repository(UserDaoImpl.COMPONENT_NAME)
public class UserDaoImpl extends AbstractGenericJpaDao<User, Long> implements UserDao {
/**
* Springs component name.
*/
public static final String COMPONENT_NAME = "userDao";
/**
* {@inheritDoc}
*
* @return Name of the query
* @see org.openwms.core.integration.jpa.AbstractGenericJpaDao#getFindAllQuery()
*/
@Override
protected String getFindAllQuery() {
return User.NQ_FIND_ALL;
}
/**
* {@inheritDoc}
*
* @return Name of the query
* @see org.openwms.core.integration.jpa.AbstractGenericJpaDao#getFindByUniqueIdQuery()
*/
@Override
protected String getFindByUniqueIdQuery() {
return User.NQ_FIND_BY_USERNAME;
}
/**
* {@inheritDoc}
*
* If no Users were found, <code>null</code> is returned.
*
* @return List of all {@link User}s
* @see org.openwms.core.integration.jpa.AbstractGenericJpaDao#findAll()
*/
@Override
public List<User> findAll() {
return super.findByPositionalParameters(User.NQ_FIND_ALL_ORDERED);
}
/**
* {@inheritDoc}
*
* Is the passed in User object is the SuperUser or <code>null</code> no
* action is performed.
*/
@Override
public void persist(User user) {
if (isSuperUser(user)) {
return;
}
super.persist(user);
}
/**
* {@inheritDoc}
*
* Is the passed in User object is the SuperUser or <code>null</code> no
* action is performed.
*/
@Override
public User save(User user) {
if (isSuperUser(user)) {
return user;
}
return super.save(user);
}
/**
* {@inheritDoc}
*
* Is the passed in User object is the SuperUser or <code>null</code> no
* action is performed.
*/
@Override
public void remove(User user) {
if (isSuperUser(user)) {
logger.info("Not allowed to remove system user, return quietly");
return;
}
for (Role role : user.getRoles()) {
role.removeUser(user);
}
user.setRoles(null);
super.remove(user);
}
/**
* {@inheritDoc}
*/
@Override
public User findByNameAndPassword(UserPassword userPassword) {
Map<String, String> params = new HashMap<String, String>();
params.put("username", userPassword.getUser().getUsername());
params.put("password", userPassword.getPassword());
List<User> users = super.findByNamedParameters(User.NQ_FIND_BY_USERNAME_PASSWORD, params);
if (users == null || users.isEmpty()) {
return null;
}
return users.get(0);
}
private boolean isSuperUser(User user) {
return (user == null || user instanceof SystemUser || SystemUser.SYSTEM_USERNAME.equals(user.getFullname()));
}
}
|
package org.jetbrains.idea.devkit.kotlin.inspections;
import com.intellij.testFramework.TestDataPath;
import org.jetbrains.idea.devkit.inspections.ComponentNotRegisteredInspectionTestBase;
import org.jetbrains.idea.devkit.kotlin.DevkitKtTestsUtil;
@TestDataPath("$CONTENT_ROOT/testData/inspections/componentNotRegistered")
public class KtComponentNotRegisteredInspectionTest extends ComponentNotRegisteredInspectionTestBase {
@Override
protected String getSourceFileExtension() {
return "kt";
}
@Override
protected String getBasePath() {
return DevkitKtTestsUtil.TESTDATA_PATH + "inspections/componentNotRegistered";
}
}
|
package edu.cornell.mannlib.vitro.webapp.visualization.freemarker.entitycomparison.cached;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.apache.commons.lang.StringEscapeUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import com.google.gson.Gson;
import com.hp.hpl.jena.query.Dataset;
import com.hp.hpl.jena.rdf.model.Model;
import edu.cornell.mannlib.vitro.webapp.beans.Portal;
import edu.cornell.mannlib.vitro.webapp.controller.VitroRequest;
import edu.cornell.mannlib.vitro.webapp.controller.freemarker.responsevalues.ResponseValues;
import edu.cornell.mannlib.vitro.webapp.controller.freemarker.responsevalues.TemplateResponseValues;
import edu.cornell.mannlib.vitro.webapp.controller.visualization.freemarker.DataVisualizationController;
import edu.cornell.mannlib.vitro.webapp.controller.visualization.freemarker.VisualizationFrameworkConstants;
import edu.cornell.mannlib.vitro.webapp.visualization.constants.VOConstants;
import edu.cornell.mannlib.vitro.webapp.visualization.exceptions.MalformedQueryParametersException;
import edu.cornell.mannlib.vitro.webapp.visualization.freemarker.entitycomparison.EntityComparisonUtilityFunctions;
import edu.cornell.mannlib.vitro.webapp.visualization.freemarker.valueobjects.Activity;
import edu.cornell.mannlib.vitro.webapp.visualization.freemarker.valueobjects.ConstructedModelTracker;
import edu.cornell.mannlib.vitro.webapp.visualization.freemarker.valueobjects.Entity;
import edu.cornell.mannlib.vitro.webapp.visualization.freemarker.valueobjects.JsonObject;
import edu.cornell.mannlib.vitro.webapp.visualization.freemarker.valueobjects.SubEntity;
import edu.cornell.mannlib.vitro.webapp.visualization.freemarker.visutils.SelectOnModelUtilities;
import edu.cornell.mannlib.vitro.webapp.visualization.freemarker.visutils.UtilityFunctions;
import edu.cornell.mannlib.vitro.webapp.visualization.freemarker.visutils.VisualizationRequestHandler;
public class TemporalGrantVisualizationRequestHandler implements
VisualizationRequestHandler {
@Override
public ResponseValues generateStandardVisualization(
VitroRequest vitroRequest, Log log, Dataset dataset)
throws MalformedQueryParametersException {
String entityURI = vitroRequest
.getParameter(VisualizationFrameworkConstants.INDIVIDUAL_URI_KEY);
if (StringUtils.isBlank(entityURI)) {
entityURI = EntityComparisonUtilityFunctions
.getStaffProvidedOrComputedHighestLevelOrganization(
log,
dataset,
vitroRequest);
}
// System.out.println("current models in the system are");
// for (Map.Entry<String, Model> entry : ConstructedModelTracker.getAllModels().entrySet()) {
// System.out.println(entry.getKey() + " -> " + entry.getValue().size());
return prepareStandaloneMarkupResponse(vitroRequest, entityURI);
}
@Override
public Map<String, String> generateDataVisualization(
VitroRequest vitroRequest, Log log, Dataset dataset)
throws MalformedQueryParametersException {
String entityURI = vitroRequest
.getParameter(VisualizationFrameworkConstants.INDIVIDUAL_URI_KEY);
/*
* This will provide the data in json format mainly used for standalone temporal vis.
* */
if (VisualizationFrameworkConstants.TEMPORAL_GRAPH_JSON_DATA_VIS_MODE
.equalsIgnoreCase(vitroRequest
.getParameter(VisualizationFrameworkConstants.VIS_MODE_KEY))) {
if (StringUtils.isNotBlank(entityURI)) {
return getSubjectEntityAndGenerateDataResponse(
vitroRequest,
log,
dataset,
entityURI,
EntityComparisonConstants.DataVisMode.JSON);
} else {
return getSubjectEntityAndGenerateDataResponse(
vitroRequest,
log,
dataset,
EntityComparisonUtilityFunctions
.getStaffProvidedOrComputedHighestLevelOrganization(
log,
dataset,
vitroRequest),
EntityComparisonConstants.DataVisMode.JSON);
}
} else {
/*
* This provides csv download files for the content in the tables.
* */
return getSubjectEntityAndGenerateDataResponse(
vitroRequest,
log,
dataset,
entityURI,
EntityComparisonConstants.DataVisMode.CSV);
}
}
private Map<String, String> prepareDataErrorResponse() {
String outputFileName = "no-organization_grants-per-year.csv";
Map<String, String> fileData = new HashMap<String, String>();
fileData.put(DataVisualizationController.FILE_NAME_KEY,
outputFileName);
fileData.put(DataVisualizationController.FILE_CONTENT_TYPE_KEY,
"application/octet-stream");
fileData.put(DataVisualizationController.FILE_CONTENT_KEY, "");
return fileData;
}
@Override
public Object generateAjaxVisualization(VitroRequest vitroRequest, Log log,
Dataset dataset) throws MalformedQueryParametersException {
throw new UnsupportedOperationException("Entity Grant Count "
+ "does not provide Ajax response.");
}
private Map<String, String> getSubjectEntityAndGenerateDataResponse(
VitroRequest vitroRequest, Log log, Dataset dataset,
String subjectEntityURI, EntityComparisonConstants.DataVisMode visMode)
throws MalformedQueryParametersException {
Entity organizationEntity = SelectOnModelUtilities
.getSubjectOrganizationHierarchy(dataset, subjectEntityURI);
if (organizationEntity.getSubEntities() == null) {
if (EntityComparisonConstants.DataVisMode.JSON.equals(visMode)) {
return prepareStandaloneDataErrorResponse();
} else {
return prepareDataErrorResponse();
}
}
Map<String, Activity> grantURIForAssociatedPeopleToVO = new HashMap<String, Activity>();
Map<String, Activity> allGrantURIToVO = new HashMap<String, Activity>();
// DataSource dataSource = DatasetFactory.create();
// dataSource.setDefaultModel(vitroRequest.getJenaOntModel());
allGrantURIToVO = SelectOnModelUtilities.getGrantsForAllSubOrganizations(dataset, organizationEntity);
Entity organizationWithAssociatedPeople = SelectOnModelUtilities
.getSubjectOrganizationAssociatedPeople(dataset, subjectEntityURI);
if (organizationWithAssociatedPeople.getSubEntities() != null) {
grantURIForAssociatedPeopleToVO = SelectOnModelUtilities
.getGrantsForAssociatedPeople(dataset, organizationWithAssociatedPeople.getSubEntities());
organizationEntity = EntityComparisonUtilityFunctions.mergeEntityIfShareSameURI(
organizationEntity,
organizationWithAssociatedPeople);
}
if (allGrantURIToVO.isEmpty() && grantURIForAssociatedPeopleToVO.isEmpty()) {
if (EntityComparisonConstants.DataVisMode.JSON.equals(visMode)) {
return prepareStandaloneDataErrorResponse();
} else {
return prepareDataErrorResponse();
}
} else {
if (EntityComparisonConstants.DataVisMode.JSON.equals(visMode)) {
return prepareStandaloneDataResponse(vitroRequest, organizationEntity);
} else {
return prepareDataResponse(organizationEntity);
}
}
}
private Map<String, String> prepareStandaloneDataErrorResponse() {
Map<String, String> fileData = new HashMap<String, String>();
fileData.put(DataVisualizationController.FILE_CONTENT_TYPE_KEY,
"application/octet-stream");
fileData.put(DataVisualizationController.FILE_CONTENT_KEY,
"{\"error\" : \"No Grants for this Organization found in VIVO.\"}");
return fileData;
}
private Map<String, String> prepareStandaloneDataResponse(
VitroRequest vitroRequest,
Entity entity) {
Map<String, String> fileData = new HashMap<String, String>();
fileData.put(DataVisualizationController.FILE_CONTENT_TYPE_KEY,
"application/octet-stream");
fileData.put(DataVisualizationController.FILE_CONTENT_KEY,
writeGrantsOverTimeJSON(vitroRequest,
entity.getSubEntities()));
return fileData;
}
/**
* Provides response when json file containing the grant count over the
* years is requested.
*
* @param entity
* @param subentities
* @param subOrganizationTypesResult
*/
private Map<String, String> prepareDataResponse(Entity entity) {
String entityLabel = entity.getEntityLabel();
/*
* To make sure that null/empty records for entity names do not cause any mischief.
* */
if (StringUtils.isBlank(entityLabel)) {
entityLabel = "no-organization";
}
String outputFileName = UtilityFunctions.slugify(entityLabel)
+ "_grants-per-year" + ".csv";
Map<String, String> fileData = new HashMap<String, String>();
fileData.put(DataVisualizationController.FILE_NAME_KEY,
outputFileName);
fileData.put(DataVisualizationController.FILE_CONTENT_TYPE_KEY,
"application/octet-stream");
fileData.put(DataVisualizationController.FILE_CONTENT_KEY,
getEntityGrantsPerYearCSVContent(entity));
return fileData;
}
private TemplateResponseValues prepareStandaloneMarkupResponse(VitroRequest vreq,
String entityURI) {
Portal portal = vreq.getPortal();
String standaloneTemplate = "entityComparisonOnGrantsStandalone.ftl";
String organizationLabel = EntityComparisonUtilityFunctions.getEntityLabelFromDAO(vreq,
entityURI);
Map<String, Object> body = new HashMap<String, Object>();
body.put("portalBean", portal);
body.put("title", organizationLabel + " - Temporal Graph Visualization");
body.put("organizationURI", entityURI);
body.put("organizationLabel", organizationLabel);
return new TemplateResponseValues(standaloneTemplate, body);
}
/**
* Function to generate a json file for year <-> grant count mapping.
* @param vreq
* @param subentities
* @param subOrganizationTypesResult
*/
private String writeGrantsOverTimeJSON(VitroRequest vreq,
Set<SubEntity> subentities) {
Gson json = new Gson();
Set<JsonObject> subEntitiesJson = new HashSet<JsonObject>();
for (SubEntity subentity : subentities) {
JsonObject entityJson = new JsonObject(
subentity.getIndividualLabel());
List<List<Integer>> yearGrantCount = new ArrayList<List<Integer>>();
for (Map.Entry<String, Integer> grantEntry : UtilityFunctions
.getYearToActivityCount(subentity.getActivities())
.entrySet()) {
List<Integer> currentGrantYear = new ArrayList<Integer>();
if (grantEntry.getKey().equals(
VOConstants.DEFAULT_GRANT_YEAR)) {
currentGrantYear.add(-1);
} else {
currentGrantYear.add(Integer.parseInt(grantEntry.getKey()));
}
currentGrantYear.add(grantEntry.getValue());
yearGrantCount.add(currentGrantYear);
}
entityJson.setYearToActivityCount(yearGrantCount);
entityJson.setOrganizationTypes(subentity.getEntityTypeLabels());
entityJson.setEntityURI(subentity.getIndividualURI());
entityJson.setLastCachedAtDateTime(subentity.getLastCachedAtDateTime());
if (subentity.getEntityClass().equals(VOConstants.EntityClassType.PERSON)) {
entityJson.setVisMode("PERSON");
} else if (subentity.getEntityClass().equals(VOConstants.EntityClassType.ORGANIZATION)) {
entityJson.setVisMode("ORGANIZATION");
}
subEntitiesJson.add(entityJson);
}
return json.toJson(subEntitiesJson);
}
private String getEntityGrantsPerYearCSVContent(Entity entity) {
StringBuilder csvFileContent = new StringBuilder();
csvFileContent.append("Entity Name, Grant Count, Entity Type\n");
for (SubEntity subEntity : entity.getSubEntities()) {
csvFileContent.append(StringEscapeUtils.escapeCsv(subEntity.getIndividualLabel()));
csvFileContent.append(", ");
csvFileContent.append(subEntity.getActivities().size());
csvFileContent.append(", ");
String allTypes = StringUtils.join(subEntity.getEntityTypeLabels(), "; ");
csvFileContent.append(StringEscapeUtils.escapeCsv(allTypes));
csvFileContent.append("\n");
}
return csvFileContent.toString();
}
}
|
package org.xwiki.diff.internal.script;
import java.util.List;
import javax.inject.Inject;
import javax.inject.Named;
import javax.inject.Singleton;
import org.xwiki.component.annotation.Component;
import org.xwiki.context.Execution;
import org.xwiki.diff.DiffConfiguration;
import org.xwiki.diff.DiffException;
import org.xwiki.diff.DiffManager;
import org.xwiki.diff.DiffResult;
import org.xwiki.diff.MergeConfiguration;
import org.xwiki.diff.MergeException;
import org.xwiki.diff.MergeResult;
import org.xwiki.diff.internal.DefaultDiffResult;
import org.xwiki.diff.internal.DefaultMergeResult;
import org.xwiki.logging.LogLevel;
import org.xwiki.logging.event.LogEvent;
import org.xwiki.script.service.ScriptService;
/**
* Provide script oriented APIs to do diff and merges.
*
* @version $Id$
* @since 4.1RC1
*/
@Component
@Named("diff")
@Singleton
public class DiffScriptService implements ScriptService
{
/**
* The key under which the last encountered error is stored in the current execution context.
*/
static final String DIFF_ERROR_KEY = "scriptservice.diff.error";
/**
* The component used to access the execution context.
*/
@Inject
private Execution execution;
/**
* The component used to create the diff.
*/
@Inject
private DiffManager diffManager;
/**
* The displayer oriented sub API.
*/
@Inject
private ScriptService diffDisplayScriptService;
/**
* @return the display oriented API
*/
public ScriptService getDisplay()
{
return this.diffDisplayScriptService;
}
/**
* Produce a diff between the two provided versions.
*
* @param <E> the type of compared elements
* @param previous the previous version of the content to compare
* @param next the next version of the content to compare
* @param configuration the configuration of the diff behavior
* @return the result of the diff
*/
public <E> DiffResult<E> diff(List<E> previous, List<E> next, DiffConfiguration<E> configuration)
{
DiffResult<E> result;
try {
result = this.diffManager.diff(previous, next, configuration);
} catch (DiffException e) {
result = new DefaultDiffResult<E>(previous, next);
result.getLog().add(new LogEvent(LogLevel.ERROR, "Failed to execute diff", null, e));
}
return result;
}
/**
* Execute a 3-way merge on provided versions.
*
* @param <E> the type of compared elements
* @param commonAncestor the common ancestor of the two versions of the content to compare
* @param next the next version of the content to compare
* @param current the current version of the content to compare
* @param configuration the configuration of the merge behavior
* @return the result of the merge
*/
public <E> MergeResult<E> merge(List<E> commonAncestor, List<E> next, List<E> current,
MergeConfiguration<E> configuration)
{
MergeResult<E> result;
try {
result = this.diffManager.merge(commonAncestor, next, current, configuration);
} catch (MergeException e) {
result = new DefaultMergeResult<E>(commonAncestor, next, current);
result.getLog().add(new LogEvent(LogLevel.ERROR, "Failed to execute merge", null, e));
}
return result;
}
/**
* Get the error generated while performing the previously called action.
*
* @return an eventual exception or {@code null} if no exception was thrown
*/
public Exception getLastError()
{
return (Exception) this.execution.getContext().getProperty(DIFF_ERROR_KEY);
}
}
|
package com.atlassian.jira.plugins.dvcs.spi.bitbucket.clientlibrary.restpoints;
import java.text.MessageFormat;
import java.util.List;
import com.atlassian.jira.plugins.dvcs.spi.bitbucket.clientlibrary.client.ClientUtils;
import com.atlassian.jira.plugins.dvcs.spi.bitbucket.clientlibrary.model.BitbucketRepository;
import com.atlassian.jira.plugins.dvcs.spi.bitbucket.clientlibrary.model.BitbucketRepositoryEnvelope;
import com.atlassian.jira.plugins.dvcs.spi.bitbucket.clientlibrary.request.RemoteRequestor;
import com.atlassian.jira.plugins.dvcs.spi.bitbucket.clientlibrary.request.RemoteResponse;
import com.google.gson.reflect.TypeToken;
public class RepositoryRemoteRestpoint
{
private final RemoteRequestor requestor;
public RepositoryRemoteRestpoint(RemoteRequestor requestor)
{
super();
this.requestor = requestor;
}
public List<BitbucketRepository> getAllRepositories(String forAccount)
{
String resourceUrl = MessageFormat.format("/users/{0}", forAccount);
RemoteResponse response = requestor.get(resourceUrl, null);
BitbucketRepositoryEnvelope envelope = ClientUtils.fromJson(response.getResponse(),
new TypeToken<BitbucketRepositoryEnvelope>(){}.getType());
return envelope.getRepositories();
}
}
|
package org.jbehave.web.examples.trader.webdriver.steps;
import org.jbehave.core.annotations.AfterScenario;
import org.jbehave.core.annotations.AfterScenario.Outcome;
import org.jbehave.web.selenium.WebDriverProvider;
import org.jbehave.web.selenium.WebDriverSteps;
public class FailingScenarioScreenshotCapture extends WebDriverSteps {
public FailingScenarioScreenshotCapture(WebDriverProvider driverProvider) {
super(driverProvider);
}
@AfterScenario(uponOutcome = Outcome.FAILURE)
public void afterScenarioFailure() throws Exception {
String screenshotPath = "target/screenshots/failed-scenario-" + System.currentTimeMillis() + ".png";
driverProvider.saveScreenshotTo(screenshotPath);
}
@AfterScenario(uponOutcome = Outcome.SUCCESS)
public void afterScenario() throws Exception {
}
}
|
package org.opencb.opencga.storage.hadoop.variant.index;
import org.apache.commons.lang3.StringUtils;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.conf.Configured;
import org.apache.hadoop.hbase.client.*;
import org.apache.hadoop.hbase.io.compress.Compression;
import org.apache.hadoop.hbase.mapreduce.MultiTableOutputFormat;
import org.apache.hadoop.hbase.mapreduce.TableMapReduceUtil;
import org.apache.hadoop.hbase.mapreduce.TableMapper;
import org.apache.hadoop.hbase.util.Bytes;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.util.GenericOptionsParser;
import org.apache.hadoop.util.Tool;
import org.apache.hadoop.util.ToolRunner;
import org.opencb.commons.datastore.core.QueryOptions;
import org.opencb.commons.datastore.core.QueryResult;
import org.opencb.opencga.storage.core.exceptions.StorageManagerException;
import org.opencb.opencga.storage.core.metadata.BatchFileOperation;
import org.opencb.opencga.storage.core.metadata.StudyConfiguration;
import org.opencb.opencga.storage.hadoop.exceptions.StorageHadoopException;
import org.opencb.opencga.storage.hadoop.utils.HBaseManager;
import org.opencb.opencga.storage.hadoop.variant.GenomeHelper;
import org.opencb.opencga.storage.hadoop.variant.HBaseStudyConfigurationManager;
import org.opencb.opencga.storage.hadoop.variant.HadoopVariantStorageManager;
import org.opencb.opencga.storage.hadoop.variant.archive.ArchiveDriver;
import org.opencb.opencga.storage.hadoop.variant.archive.ArchiveHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;
/**
* @author Matthias Haimel mh719+git@cam.ac.uk
*
*/
public abstract class AbstractVariantTableDriver extends Configured implements Tool {
protected final Logger LOG = LoggerFactory.getLogger(this.getClass());
public static final String CONFIG_VARIANT_FILE_IDS = "opencga.variant.input.file_ids";
public static final String CONFIG_VARIANT_TABLE_NAME = "opencga.variant.table.name";
public static final String CONFIG_VARIANT_TABLE_COMPRESSION = "opencga.variant.table.compression";
public static final String TIMESTAMP = "opencga.variant.table.timestamp";
private VariantTableHelper variantTablehelper;
protected HBaseStudyConfigurationManager scm;
protected StudyConfiguration studyConfiguration;
public AbstractVariantTableDriver() { /* nothing */ }
/**
* @param conf Configuration.
*/
public AbstractVariantTableDriver(Configuration conf) {
super(conf);
}
@SuppressWarnings ("rawtypes")
protected abstract Class<? extends TableMapper> getMapperClass();
@Override
public int run(String[] args) throws Exception {
Configuration conf = getConf();
String inTable = conf.get(ArchiveDriver.CONFIG_ARCHIVE_TABLE_NAME, StringUtils.EMPTY);
String outTable = conf.get(CONFIG_VARIANT_TABLE_NAME, StringUtils.EMPTY);
String[] fileArr = argFileArray();
Integer studyId = conf.getInt(GenomeHelper.CONFIG_STUDY_ID, -1);
// Validate parameters CHECK
if (StringUtils.isEmpty(inTable)) {
throw new IllegalArgumentException("No input hbase table basename specified!!!");
}
if (StringUtils.isEmpty(outTable)) {
throw new IllegalArgumentException("No output hbase table specified!!!");
}
if (inTable.equals(outTable)) {
throw new IllegalArgumentException("Input and Output tables must be different");
}
if (studyId < 0) {
throw new IllegalArgumentException("No Study id specified!!!");
}
int fileCnt = fileArr.length;
if (fileCnt == 0) {
throw new IllegalArgumentException("No files specified");
}
List<Integer> fileIds = new ArrayList<>(fileArr.length);
for (String fileIdStr : fileArr) {
int id = Integer.parseInt(fileIdStr);
fileIds.add(id);
}
getLog().info(String.format("Use table %s as input", inTable));
GenomeHelper.setStudyId(conf, studyId);
VariantTableHelper.setOutputTableName(conf, outTable);
VariantTableHelper.setInputTableName(conf, inTable);
VariantTableHelper gh = getHelper();
// Validate input CHECK
HBaseManager hBaseManager = gh.getHBaseManager();
if (!hBaseManager.tableExists(inTable)) {
throw new IllegalArgumentException(String.format("Input table %s does not exist!!!", inTable));
}
check(fileIds);
// JOB setup
Job job = createJob(outTable, fileArr);
// QUERY design
Scan scan = createScan(gh, fileArr);
// set other scan attrs
boolean addDependencyJar = conf.getBoolean(GenomeHelper.CONFIG_HBASE_ADD_DEPENDENCY_JARS, true);
initMapReduceJob(inTable, outTable, job, scan, addDependencyJar);
boolean succeed = executeJob(job);
if (!succeed) {
getLog().error("error with job!");
}
if (succeed) {
onSuccess();
} else {
onError();
}
getStudyConfigurationManager().close();
return succeed ? 0 : 1;
}
protected void check(List<Integer> fileIds) throws StorageManagerException, IOException {
Configuration conf = getConf();
HBaseStudyConfigurationManager scm = getStudyConfigurationManager();
long lock = scm.lockStudy(getHelper().getStudyId());
studyConfiguration = loadStudyConfiguration();
List<BatchFileOperation> batches = studyConfiguration.getBatches();
BatchFileOperation batchFileOperation;
if (!batches.isEmpty()) {
batchFileOperation = batches.get(batches.size() - 1);
BatchFileOperation.Status currentStatus = batchFileOperation.currentStatus();
if (currentStatus != null) {
switch (currentStatus) {
case READY:
batchFileOperation = new BatchFileOperation(getJobOperationName(), fileIds, batchFileOperation.getTimestamp() + 1);
break;
case RUNNING:
if (!conf.getBoolean(HadoopVariantStorageManager.HADOOP_LOAD_VARIANT_RESUME, false)) {
throw new StorageHadoopException("Unable to process a new batch. Ongoing batch operation: "
+ batchFileOperation);
}
// Do not break. Resuming last loading, go to error case.
case ERROR:
if (batchFileOperation.getFileIds().equals(fileIds)) {
LOG.info("Resuming Last batch loading due to error.");
} else {
throw new StorageHadoopException("Unable to resume last batch operation. "
+ "Must have the same files from the previous batch: " + batchFileOperation);
}
break;
default:
throw new IllegalArgumentException("Unknown Status " + currentStatus);
}
}
} else {
batchFileOperation = new BatchFileOperation(getJobOperationName(), fileIds, 1);
}
batchFileOperation.addStatus(Calendar.getInstance().getTime(), BatchFileOperation.Status.RUNNING);
batches.add(batchFileOperation);
scm.updateStudyConfiguration(studyConfiguration, new QueryOptions());
scm.unLockStudy(studyConfiguration.getStudyId(), lock);
conf.setLong(TIMESTAMP, batchFileOperation.getTimestamp());
}
protected void onError() {
try {
HBaseStudyConfigurationManager scm = getStudyConfigurationManager();
long lock = scm.lockStudy(getHelper().getStudyId());
studyConfiguration = scm.getStudyConfiguration(studyConfiguration.getStudyId(), null).first();
BatchFileOperation batchFileOperation = studyConfiguration.getBatches().get(studyConfiguration.getBatches().size() - 1);
batchFileOperation.addStatus(Calendar.getInstance().getTime(), BatchFileOperation.Status.ERROR);
scm.updateStudyConfiguration(studyConfiguration, new QueryOptions());
scm.unLockStudy(studyConfiguration.getStudyId(), lock);
} catch (IOException | StorageManagerException e) {
e.printStackTrace();
}
}
protected void onSuccess() {
try {
HBaseStudyConfigurationManager scm = getStudyConfigurationManager();
long lock = scm.lockStudy(getHelper().getStudyId());
studyConfiguration = scm.getStudyConfiguration(studyConfiguration.getStudyId(), null).first();
BatchFileOperation batchFileOperation = studyConfiguration.getBatches().get(studyConfiguration.getBatches().size() - 1);
batchFileOperation.addStatus(Calendar.getInstance().getTime(), BatchFileOperation.Status.READY);
scm.updateStudyConfiguration(studyConfiguration, new QueryOptions());
scm.unLockStudy(studyConfiguration.getStudyId(), lock);
} catch (IOException | StorageManagerException e) {
e.printStackTrace();
}
}
/**
* Give the name of the action that the job is doing.
*
* Used to create the jobName and as {@link BatchFileOperation#operationName}
*
* e.g. : "Delete", "Load", "Annotate", ...
*
* @return Job action
*/
protected abstract String getJobOperationName();
protected String[] argFileArray() {
return getConf().getStrings(CONFIG_VARIANT_FILE_IDS, new String[0]);
}
protected VariantTableHelper getHelper() {
if (null == variantTablehelper) {
variantTablehelper = new VariantTableHelper(getConf());
}
return variantTablehelper;
}
protected void initMapReduceJob(String inTable, String outTable, Job job, Scan scan, boolean addDependencyJar) throws IOException {
TableMapReduceUtil.initTableMapperJob(
inTable, // input table
scan, // Scan instance to control CF and attribute selection
getMapperClass(), // mapper class
null, // mapper output key
null, // mapper output value
job,
addDependencyJar);
TableMapReduceUtil.initTableReducerJob(
outTable, // output table
null, // reducer class
job,
null, null, null, null,
addDependencyJar);
job.setNumReduceTasks(0);
job.setOutputFormatClass(MultiTableOutputFormat.class);
}
protected boolean executeJob(Job job) throws IOException, InterruptedException, ClassNotFoundException {
Thread hook = new Thread(() -> {
try {
if (!job.isComplete()) {
job.killJob();
}
onError();
} catch (IOException e) {
e.printStackTrace();
}
});
Runtime.getRuntime().addShutdownHook(hook);
boolean succeed = job.waitForCompletion(true);
Runtime.getRuntime().removeShutdownHook(hook);
return succeed;
}
protected Logger getLog() {
return LOG;
}
protected Job createJob(String outTable, String[] fileArr) throws IOException {
Job job = Job.getInstance(getConf(), "opencga: " + getJobOperationName() + " file " + Arrays.toString(fileArr)
+ " on VariantTable '" + outTable + "'");
job.getConfiguration().set("mapreduce.job.user.classpath.first", "true");
job.setJarByClass(getMapperClass()); // class that contains mapper
return job;
}
protected Scan createScan(VariantTableHelper gh, String[] fileArr) {
Scan scan = new Scan();
scan.setCaching(100); // 1 is the default in Scan, which will be bad for MapReduce jobs
scan.setCacheBlocks(false); // don't set to true for MR jobs
// specify return columns (file IDs)
for (String fileIdStr : fileArr) {
int id = Integer.parseInt(fileIdStr);
scan.addColumn(gh.getColumnFamily(), Bytes.toBytes(ArchiveHelper.getColumnName(id)));
}
scan.addColumn(gh.getColumnFamily(), GenomeHelper.VARIANT_COLUMN_B);
return scan;
}
protected StudyConfiguration loadStudyConfiguration() throws IOException {
HBaseStudyConfigurationManager scm = getStudyConfigurationManager();
int studyId = getHelper().getStudyId();
QueryResult<StudyConfiguration> res = scm.getStudyConfiguration(studyId, new QueryOptions());
if (res.getResult().size() != 1) {
throw new IllegalStateException("StudyConfiguration " + studyId + " not found! " + res.getResult().size());
}
return res.first();
}
protected HBaseStudyConfigurationManager getStudyConfigurationManager() throws IOException {
if (scm == null) {
byte[] outTable = getHelper().getOutputTable();
scm = new HBaseStudyConfigurationManager(Bytes.toString(outTable), getConf(), null);
}
return scm;
}
public static String buildCommandLineArgs(String server, String inputTable, String outputTable, int studyId,
List<Integer> fileIds, Map<String, Object> other) {
StringBuilder stringBuilder = new StringBuilder().append(server).append(' ').append(inputTable).append(' ')
.append(outputTable).append(' ').append(studyId).append(' ');
stringBuilder.append(fileIds.stream().map(Object::toString).collect(Collectors.joining(",")));
ArchiveDriver.addOtherParams(other, stringBuilder);
return stringBuilder.toString();
}
public static boolean createVariantTableIfNeeded(GenomeHelper genomeHelper, String tableName) throws IOException {
try (Connection con = ConnectionFactory.createConnection(genomeHelper.getConf())) {
return createVariantTableIfNeeded(genomeHelper, tableName, con);
}
}
public static boolean createVariantTableIfNeeded(GenomeHelper genomeHelper, String tableName, Connection con) throws IOException {
return genomeHelper.getHBaseManager().createTableIfNeeded(con, tableName, genomeHelper.getColumnFamily(),
Compression.getCompressionAlgorithmByName(
genomeHelper.getConf().get(CONFIG_VARIANT_TABLE_COMPRESSION, Compression.Algorithm.SNAPPY.getName())));
}
public static String[] configure(String[] args, Configuration conf) throws Exception {
if (conf == null) {
throw new NullPointerException("Provided Configuration is null!!!");
}
GenericOptionsParser parser = new GenericOptionsParser(conf, args);
//get the args w/o generic hadoop args
String[] toolArgs = parser.getRemainingArgs();
int fixedSizeArgs = 5;
if (toolArgs.length < fixedSizeArgs || (toolArgs.length - fixedSizeArgs) % 2 != 0) {
System.err.printf("Usage: %s [generic options] <server> <input-table> <output-table> <studyId> <fileIds>"
+ " [<key> <value>]*\n",
AbstractVariantTableDriver.class.getSimpleName());
System.err.println("Found " + Arrays.toString(toolArgs));
ToolRunner.printGenericCommandUsage(System.err);
return null;
}
HBaseManager.addHBaseSettings(conf, toolArgs[0]);
conf.set(ArchiveDriver.CONFIG_ARCHIVE_TABLE_NAME, toolArgs[1]);
conf.set(CONFIG_VARIANT_TABLE_NAME, toolArgs[2]);
conf.set(GenomeHelper.CONFIG_STUDY_ID, toolArgs[3]);
conf.setStrings(CONFIG_VARIANT_FILE_IDS, toolArgs[4].split(","));
for (int i = fixedSizeArgs; i < toolArgs.length; i = i + 2) {
conf.set(toolArgs[i], toolArgs[i + 1]);
}
return toolArgs;
}
}
|
package com.azure.messaging.servicebus.implementation;
import com.azure.core.amqp.AmqpConnection;
import com.azure.core.amqp.AmqpEndpointState;
import com.azure.core.amqp.AmqpRetryPolicy;
import com.azure.core.amqp.exception.AmqpErrorCondition;
import com.azure.core.amqp.exception.AmqpException;
import com.azure.core.amqp.implementation.ExceptionUtil;
import com.azure.core.amqp.implementation.ReactorProvider;
import com.azure.core.amqp.implementation.ReactorReceiver;
import com.azure.core.amqp.implementation.TokenManager;
import com.azure.core.amqp.implementation.handler.ReceiveLinkHandler;
import com.azure.core.util.logging.ClientLogger;
import com.azure.messaging.servicebus.models.ServiceBusReceiveMode;
import org.apache.qpid.proton.Proton;
import org.apache.qpid.proton.amqp.Symbol;
import org.apache.qpid.proton.amqp.messaging.Accepted;
import org.apache.qpid.proton.amqp.messaging.Outcome;
import org.apache.qpid.proton.amqp.messaging.Rejected;
import org.apache.qpid.proton.amqp.messaging.Released;
import org.apache.qpid.proton.amqp.messaging.Source;
import org.apache.qpid.proton.amqp.transaction.TransactionalState;
import org.apache.qpid.proton.amqp.transport.DeliveryState;
import org.apache.qpid.proton.amqp.transport.ErrorCondition;
import org.apache.qpid.proton.amqp.transport.SenderSettleMode;
import org.apache.qpid.proton.engine.Delivery;
import org.apache.qpid.proton.engine.Receiver;
import org.apache.qpid.proton.message.Message;
import reactor.core.Disposable;
import reactor.core.Exceptions;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import reactor.core.publisher.MonoSink;
import reactor.core.scheduler.Schedulers;
import java.io.IOException;
import java.time.Duration;
import java.time.Instant;
import java.time.OffsetDateTime;
import java.time.ZoneOffset;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.StringJoiner;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import static com.azure.core.util.FluxUtil.monoError;
import static com.azure.messaging.servicebus.implementation.MessageUtils.LOCK_TOKEN_SIZE;
import static com.azure.messaging.servicebus.implementation.ServiceBusReactorSession.LOCKED_UNTIL_UTC;
import static com.azure.messaging.servicebus.implementation.ServiceBusReactorSession.SESSION_FILTER;
/**
* A proton-j receiver for Service Bus.
*/
public class ServiceBusReactorReceiver extends ReactorReceiver implements ServiceBusReceiveLink {
private static final Message EMPTY_MESSAGE = Proton.message();
private final ClientLogger logger = new ClientLogger(ServiceBusReactorReceiver.class);
private final ConcurrentHashMap<String, Delivery> unsettledDeliveries = new ConcurrentHashMap<>();
private final ConcurrentHashMap<String, UpdateDispositionWorkItem> pendingUpdates = new ConcurrentHashMap<>();
private final AtomicBoolean isDisposed = new AtomicBoolean();
private final Disposable subscription;
private final Receiver receiver;
/**
* Indicates whether the message has already been settled from the sender side. This is the case when {@link
* ServiceBusReceiveMode#RECEIVE_AND_DELETE} is used.
*/
private final boolean isSettled;
private final Duration timeout;
private final AmqpRetryPolicy retryPolicy;
private final ReceiveLinkHandler handler;
private final ReactorProvider provider;
private final Mono<String> sessionIdMono;
private final Mono<OffsetDateTime> sessionLockedUntil;
public ServiceBusReactorReceiver(AmqpConnection connection, String entityPath, Receiver receiver,
ReceiveLinkHandler handler, TokenManager tokenManager, ReactorProvider provider, Duration timeout,
AmqpRetryPolicy retryPolicy) {
super(connection, entityPath, receiver, handler, tokenManager, provider.getReactorDispatcher(),
retryPolicy.getRetryOptions());
this.receiver = receiver;
this.handler = handler;
this.provider = provider;
this.isSettled = receiver.getSenderSettleMode() == SenderSettleMode.SETTLED;
this.timeout = timeout;
this.retryPolicy = retryPolicy;
this.subscription = Flux.interval(timeout).subscribe(i -> cleanupWorkItems());
this.sessionIdMono = getEndpointStates().filter(x -> x == AmqpEndpointState.ACTIVE)
.next()
.flatMap(state -> {
@SuppressWarnings("unchecked") final Map<Symbol, Object> remoteSource =
((Source) receiver.getRemoteSource()).getFilter();
final Object value = remoteSource.get(SESSION_FILTER);
if (value == null) {
logger.info("entityPath[{}], linkName[{}]. There is no session id.", entityPath, getLinkName());
return Mono.empty();
}
final String actualSessionId = String.valueOf(value);
return Mono.just(actualSessionId);
})
.cache(value -> Duration.ofMillis(Long.MAX_VALUE), error -> Duration.ZERO, () -> Duration.ZERO);
this.sessionLockedUntil = getEndpointStates().filter(x -> x == AmqpEndpointState.ACTIVE)
.next()
.map(state -> {
if (receiver.getRemoteProperties() != null
&& receiver.getRemoteProperties().containsKey(LOCKED_UNTIL_UTC)) {
final long ticks = (long) receiver.getRemoteProperties().get(LOCKED_UNTIL_UTC);
return MessageUtils.convertDotNetTicksToOffsetDateTime(ticks);
} else {
logger.info("entityPath[{}], linkName[{}]. Locked until not set.", entityPath, getLinkName());
return Instant.EPOCH.atOffset(ZoneOffset.UTC);
}
})
.cache(value -> Duration.ofMillis(Long.MAX_VALUE), error -> Duration.ZERO, () -> Duration.ZERO);
}
@Override
public Mono<Void> updateDisposition(String lockToken, DeliveryState deliveryState) {
if (isDisposed.get()) {
return monoError(logger, new IllegalStateException("Cannot perform operations on a disposed receiver."));
}
return updateDispositionInternal(lockToken, deliveryState);
}
@Override
public Flux<Message> receive() {
// Remove empty update disposition messages. The deliveries themselves are ACKs with no message.
return super.receive()
.filter(message -> message != EMPTY_MESSAGE)
.publishOn(Schedulers.boundedElastic());
}
@Override
public Mono<String> getSessionId() {
return sessionIdMono;
}
@Override
public Mono<OffsetDateTime> getSessionLockedUntil() {
return sessionLockedUntil;
}
@Override
public Mono<Void> closeAsync() {
if (isDisposed.getAndSet(true)) {
return super.closeAsync();
}
cleanupWorkItems();
final Mono<Void> disposeMono;
if (!pendingUpdates.isEmpty()) {
final List<Mono<Void>> pending = new ArrayList<>();
final StringJoiner builder = new StringJoiner(", ");
for (UpdateDispositionWorkItem workItem : pendingUpdates.values()) {
if (workItem.hasTimedout()) {
continue;
}
if (workItem.getDeliveryState() instanceof TransactionalState) {
pending.add(updateDispositionInternal(workItem.getLockToken(), Released.getInstance()));
} else {
pending.add(workItem.getMono());
}
builder.add(workItem.getLockToken());
}
logger.info("Waiting for pending updates to complete. Locks: {}", builder.toString());
disposeMono = Mono.when(pending);
} else {
disposeMono = Mono.empty();
}
return disposeMono.onErrorResume(error -> {
logger.info("There was an exception while disposing of all links.", error);
return Mono.empty();
}).doFinally(signal -> subscription.dispose()).then(super.closeAsync());
}
@Override
protected Message decodeDelivery(Delivery delivery) {
final byte[] deliveryTag = delivery.getTag();
final UUID lockToken;
if (deliveryTag != null && deliveryTag.length == LOCK_TOKEN_SIZE) {
lockToken = MessageUtils.convertDotNetBytesToUUID(deliveryTag);
} else {
lockToken = MessageUtils.ZERO_LOCK_TOKEN;
}
final String lockTokenString = lockToken.toString();
// There is no lock token associated with this delivery, or the lock token is not in the unsettledDeliveries.
if (lockToken == MessageUtils.ZERO_LOCK_TOKEN || !unsettledDeliveries.containsKey(lockTokenString)) {
final int messageSize = delivery.pending();
final byte[] buffer = new byte[messageSize];
final int read = receiver.recv(buffer, 0, messageSize);
final Message message = Proton.message();
message.decode(buffer, 0, read);
// The delivery was already settled from the message broker.
// This occurs in the case of receive and delete.
if (isSettled) {
delivery.disposition(Accepted.getInstance());
delivery.settle();
} else {
unsettledDeliveries.putIfAbsent(lockToken.toString(), delivery);
receiver.advance();
}
return new MessageWithLockToken(message, lockToken);
} else {
updateOutcome(lockTokenString, delivery);
// Return empty update disposition messages. The deliveries themselves are ACKs. There is no actual message
// to propagate.
return EMPTY_MESSAGE;
}
}
private Mono<Void> updateDispositionInternal(String lockToken, DeliveryState deliveryState) {
final Delivery unsettled = unsettledDeliveries.get(lockToken);
if (unsettled == null) {
logger.warning("entityPath[{}], linkName[{}], deliveryTag[{}]. Delivery not found to update disposition.",
getEntityPath(), getLinkName(), lockToken);
return monoError(logger, Exceptions.propagate(new IllegalArgumentException(
"Delivery not on receive link.")));
}
final UpdateDispositionWorkItem workItem = new UpdateDispositionWorkItem(lockToken, deliveryState, timeout);
final Mono<Void> result = Mono.<Void>create(sink -> {
workItem.start(sink);
try {
provider.getReactorDispatcher().invoke(() -> {
unsettled.disposition(deliveryState);
pendingUpdates.put(lockToken, workItem);
});
} catch (IOException error) {
sink.error(new AmqpException(false, "updateDisposition failed while dispatching to Reactor.",
error, handler.getErrorContext(receiver)));
}
}).cache(); // cache because closeAsync use `when` to subscribe this Mono again.
workItem.setMono(result);
return result;
}
/**
* Updates the outcome of a delivery. This occurs when a message is being settled from the receiver side.
* @param delivery Delivery to update.
*/
private void updateOutcome(String lockToken, Delivery delivery) {
final DeliveryState remoteState = delivery.getRemoteState();
logger.verbose("entityPath[{}], linkName[{}], deliveryTag[{}], state[{}] Received update disposition delivery.",
getEntityPath(), getLinkName(), lockToken, remoteState);
final Outcome remoteOutcome;
if (remoteState instanceof Outcome) {
remoteOutcome = (Outcome) remoteState;
} else if (remoteState instanceof TransactionalState) {
remoteOutcome = ((TransactionalState) remoteState).getOutcome();
} else {
remoteOutcome = null;
}
if (remoteOutcome == null) {
logger.warning("linkName[{}], deliveryTag[{}]. No outcome associated with delivery. Delivery: {}",
getLinkName(), lockToken, delivery);
return;
}
final UpdateDispositionWorkItem workItem = pendingUpdates.get(lockToken);
if (workItem == null) {
logger.warning("linkName[{}], deliveryTag[{}]. No pending update for delivery. Delivery: {}",
getLinkName(), lockToken, delivery);
return;
}
// If the statuses match, then we settle the delivery and move on.
if (remoteState.getType() == workItem.getDeliveryState().getType()) {
completeWorkItem(lockToken, delivery, workItem.getSink(), null);
return;
}
logger.info("Received delivery '{}' state '{}' doesn't match expected state '{}'",
lockToken, remoteState, workItem.getDeliveryState());
switch (remoteState.getType()) {
case Rejected:
final Rejected rejected = (Rejected) remoteOutcome;
final ErrorCondition errorCondition = rejected.getError();
final Throwable exception = ExceptionUtil.toException(errorCondition.getCondition().toString(),
errorCondition.getDescription(), handler.getErrorContext(receiver));
final Duration retry = retryPolicy.calculateRetryDelay(exception, workItem.incrementRetry());
if (retry == null) {
logger.info("deliveryTag[{}], state[{}]. Retry attempts exhausted.", lockToken, exception);
completeWorkItem(lockToken, delivery, workItem.getSink(), exception);
} else {
workItem.setLastException(exception);
workItem.resetStartTime();
try {
provider.getReactorDispatcher().invoke(() -> delivery.disposition(workItem.getDeliveryState()));
} catch (IOException error) {
final Throwable amqpException = logger.logExceptionAsError(new AmqpException(false,
"linkName[%s], deliveryTag[%s]. Retrying updateDisposition failed to dispatch to Reactor.",
error, handler.getErrorContext(receiver)));
completeWorkItem(lockToken, delivery, workItem.getSink(), amqpException);
}
}
break;
case Released:
final Throwable cancelled = new AmqpException(false, AmqpErrorCondition.OPERATION_CANCELLED,
"AMQP layer unexpectedly aborted or disconnected.", handler.getErrorContext(receiver));
logger.info("deliveryTag[{}], state[{}]. Completing pending updateState operation with exception.",
lockToken, remoteState.getType(), cancelled);
completeWorkItem(lockToken, delivery, workItem.getSink(), cancelled);
break;
default:
final AmqpException error = new AmqpException(false, remoteOutcome.toString(),
handler.getErrorContext(receiver));
logger.info("deliveryTag[{}], state[{}] Completing pending updateState operation with exception.",
lockToken, remoteState.getType(), error);
completeWorkItem(lockToken, delivery, workItem.getSink(), error);
break;
}
}
private void cleanupWorkItems() {
logger.verbose("linkName[{}]: Cleaning timed out update work tasks.", getLinkName());
pendingUpdates.forEach((key, value) -> {
if (value == null || !value.hasTimedout()) {
return;
}
pendingUpdates.remove(key);
final Throwable error = value.getLastException() != null
? value.getLastException()
: new AmqpException(true, AmqpErrorCondition.TIMEOUT_ERROR, "Update disposition request timed out.",
handler.getErrorContext(receiver));
completeWorkItem(key, null, value.getSink(), error);
});
}
private void completeWorkItem(String lockToken, Delivery delivery, MonoSink<Void> sink, Throwable error) {
final boolean isSettled = delivery != null && delivery.remotelySettled();
if (isSettled) {
delivery.settle();
}
if (error != null) {
final Throwable loggedError = error instanceof RuntimeException
? logger.logExceptionAsError((RuntimeException) error)
: error;
sink.error(loggedError);
} else {
sink.success();
}
if (isSettled) {
pendingUpdates.remove(lockToken);
unsettledDeliveries.remove(lockToken);
}
}
private static final class UpdateDispositionWorkItem {
private final String lockToken;
private final DeliveryState state;
private final Duration timeout;
private final AtomicInteger retryAttempts = new AtomicInteger();
private final AtomicBoolean isDisposed = new AtomicBoolean();
private Mono<Void> mono;
private Instant expirationTime;
private MonoSink<Void> sink;
private Throwable throwable;
private UpdateDispositionWorkItem(String lockToken, DeliveryState state, Duration timeout) {
this.lockToken = lockToken;
this.state = state;
this.timeout = timeout;
}
private boolean hasTimedout() {
return expirationTime.isBefore(Instant.now());
}
private void resetStartTime() {
this.expirationTime = Instant.now().plus(timeout);
}
private int incrementRetry() {
return retryAttempts.incrementAndGet();
}
private Throwable getLastException() {
return throwable;
}
private void setLastException(Throwable throwable) {
this.throwable = throwable;
}
private void setMono(Mono<Void> mono) {
this.mono = mono;
}
private Mono<Void> getMono() {
return mono;
}
private MonoSink<Void> getSink() {
return sink;
}
private void start(MonoSink<Void> sink) {
Objects.requireNonNull(sink, "'sink' cannot be null.");
this.sink = sink;
this.sink.onDispose(() -> isDisposed.set(true));
this.sink.onCancel(() -> isDisposed.set(true));
resetStartTime();
}
private DeliveryState getDeliveryState() {
return state;
}
public String getLockToken() {
return lockToken;
}
}
}
|
package org.xwiki.test;
import java.lang.reflect.Method;
import java.lang.reflect.Type;
import org.xwiki.component.embed.EmbeddableComponentManager;
import org.xwiki.component.internal.StackingComponentEventManager;
import org.xwiki.component.manager.ComponentLookupException;
import org.xwiki.configuration.internal.MemoryConfigurationSource;
import org.xwiki.observation.ObservationManager;
import org.xwiki.test.annotation.AfterComponent;
import org.xwiki.test.annotation.BeforeComponent;
import org.xwiki.test.internal.ComponentRegistrator;
/**
* Initialize a Component Manager and uses the {@link org.xwiki.test.annotation.AllComponents} and
* {@link org.xwiki.test.annotation.ComponentList} annotations to decide what components to discover and register.
* <p>
* Also offers helper APIs to register components and in-memory configuration sources.
*
* @version $Id$
* @since 5.1RC1
*/
public class TestComponentManager extends EmbeddableComponentManager
{
/**
* Used to register components.
*/
protected ComponentRegistrator componentRegistrator = new ComponentRegistrator();
/**
* Register in-memory data source for the default and "xwikiproperties" configuration sources.
*
* @return the in-memory configuration source used for both default and "xwikiproperties" component hints
* @throws Exception in case the registration fails
*/
public MemoryConfigurationSource registerMemoryConfigurationSource() throws Exception
{
return this.componentRegistrator.registerMemoryConfigurationSource(this);
}
/**
* Registers a component.
*
* @param roleType the type of the component role to register
* @param roleHint the role hint of the component to register
* @param instance the instance to register
* @throws Exception in case of an error during registration
*/
public void registerComponent(Type roleType, String roleHint, Object instance) throws Exception
{
this.componentRegistrator.registerComponent(roleType, roleHint, instance, this);
}
/**
* Registers a component (with a default role hint).
*
* @param roleType the type of the component role to register
* @param instance the instance to register
* @throws Exception in case of an error during registration
*/
public void registerComponent(Type roleType, Object instance) throws Exception
{
this.componentRegistrator.registerComponent(roleType, instance, this);
}
/**
* Register components associated to the provided class.
*
* @param testClass the class containing the annotations
* @throws Exception in case of an error during registration
* @since 5.2M1
*/
public void registerComponent(Class<?> testClass) throws Exception
{
this.componentRegistrator.registerComponent(testClass, this);
}
/**
* Initialize the test component manager by registering components based on the presence of
* {@link org.xwiki.test.annotation.AllComponents} and {@link org.xwiki.test.annotation.ComponentList} annotations.
* Also calls methods annotated with {@link BeforeComponent} and {@link AfterComponent}.
*
* @param testClassInstance the test instance on which the annotations are present
* @throws Exception if an error happens during initialization
*/
public void initializeTest(Object testClassInstance) throws Exception
{
Class<?> testClass = testClassInstance.getClass();
// If there are methods annotated with the BeforeComponent annotation then call them. This gives an
// opportunity for the test to register some components *before* we register the other components below.
for (Method declaredMethod : testClass.getMethods()) {
if (declaredMethod.isAnnotationPresent(BeforeComponent.class)) {
declaredMethod.invoke(testClassInstance);
}
}
this.componentRegistrator.registerComponents(testClass, this);
// If there are methods annotated with the AfterComponent annotation then call them. This gives an
// opportunity to override or modify some components *after* they are actually used.
for (Method declaredMethod : testClass.getMethods()) {
if (declaredMethod.isAnnotationPresent(AfterComponent.class)) {
declaredMethod.invoke(testClassInstance);
}
}
}
/**
* Enabled notification of component descriptor registration/unregistration.
*
* @throws ComponentLookupException when failing to lookup {@link ObservationManager} component
*/
public void notifyComponentDescriptorEvent() throws ComponentLookupException
{
// Set component event manager if available
if (hasComponent(ObservationManager.class)) {
StackingComponentEventManager eventManager = new StackingComponentEventManager();
eventManager.setObservationManager(this.<ObservationManager>getInstance(ObservationManager.class));
eventManager.shouldStack(false);
setComponentEventManager(eventManager);
}
}
/**
* Cleans up the test component manager by disposing components registered in it.
*
* @throws Exception if an error happens during clean up
*/
public void shutdownTest() throws Exception
{
// Make sure to dispose all Disposable components in case they have resources/static to free
dispose();
}
}
|
package org.xwiki.validator;
import java.util.Arrays;
import java.util.List;
import java.util.ResourceBundle;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.commons.collections.ListUtils;
import org.apache.commons.lang3.StringUtils;
import org.jsoup.nodes.DocumentType;
import org.jsoup.nodes.Element;
import org.jsoup.nodes.Node;
import org.jsoup.select.Elements;
import org.w3c.dom.Document;
import org.xwiki.validator.ValidationError.Type;
import org.xwiki.validator.framework.AbstractHTML5Validator;
/**
* Validator allowing to validate (X)HTML content against Dutch Web Guidelines.
* <p>
*"There are internationally recognized agreements for creating web sites, known as 125 quality requirements standards
* warrants a significantly better website. The Netherlands government has assembled these international standards in a
* quality model called the Web Guidelines. This quality model comprises 125 quality requirements for the benefit of
* better websites."
* </p>
*
* @version $Id$
*/
public class HTML5DutchWebGuidelinesValidator extends AbstractHTML5Validator
{
/**
* String used to identify the charset in the content-type meta.
*/
private static final String CONTENT_CHARSET_FRAGMENT = "charset=";
/**
* Character used to mark the beginning of the query string in a URL.
*/
private static final String QUERY_STRING_SEPARATOR = "?";
/**
* Message resources.
*/
private ResourceBundle messages = ResourceBundle.getBundle("DutchWebGuidelines");
/**
* Constructor.
*/
public HTML5DutchWebGuidelinesValidator()
{
super();
}
@Override
public String getName()
{
return "HTML5 Dutch Web Guidelines";
}
/**
* Add an error to the list of errors using our message resources.
*
* @param errorType type of the error
* @param line line where the error occurred
* @param column where the error occurred
* @param key key to retrieve the value from in the message properties
*/
@Override
protected void addError(Type errorType, int line, int column, String key)
{
super.addError(errorType, line, column, this.messages.getString(key));
}
@Override
protected void validate(Document document)
{
// RPD 1
validateRpd1s1();
validateRpd1s2();
validateRpd1s3();
// RPD 2
validateRpd2s1();
validateRpd2s2();
validateRpd2s3();
validateRpd2s4();
validateRpd2s5();
validateRpd2s6();
validateRpd2s7();
validateRpd2s8();
validateRpd2s9();
// RPD 3
validateRpd3s1();
validateRpd3s2();
validateRpd3s3();
validateRpd3s4();
validateRpd3s5();
validateRpd3s6();
validateRpd3s7();
validateRpd3s8();
validateRpd3s9();
validateRpd3s10();
validateRpd3s11();
validateRpd3s12();
validateRpd3s13();
validateRpd3s14();
validateRpd3s15();
// RPD 4
validateRpd4s1();
validateRpd4s2();
validateRpd4s3();
validateRpd4s4();
validateRpd4s5();
validateRpd4s6();
validateRpd4s7();
// RPD 5
validateRpd5s1();
// RPD 6
validateRpd6s1();
validateRpd6s2();
// RPD 7
validateRpd7s1();
validateRpd7s2();
validateRpd7s3();
validateRpd7s4();
validateRpd7s5();
validateRpd7s6();
validateRpd7s7();
// RPD 8
validateRpd8s1();
validateRpd8s2();
validateRpd8s3();
validateRpd8s4();
validateRpd8s5();
validateRpd8s6();
validateRpd8s7();
validateRpd8s8();
validateRpd8s9();
validateRpd8s10();
validateRpd8s11();
validateRpd8s12();
validateRpd8s13();
validateRpd8s14();
validateRpd8s15();
validateRpd8s16();
validateRpd8s17();
validateRpd8s18();
validateRpd8s19();
validateRpd8s20();
validateRpd8s21();
validateRpd8s22();
validateRpd8s23();
// RPD 9
validateRpd9s1();
validateRpd9s2();
// RPD 10
validateRpd10s1();
validateRpd10s2();
validateRpd10s3();
// RPD 11
validateRpd11s1();
validateRpd11s2();
validateRpd11s3();
validateRpd11s4();
validateRpd11s5();
validateRpd11s6();
validateRpd11s7();
validateRpd11s8();
validateRpd11s9();
validateRpd11s10();
// RPD 12
validateRpd12s1();
// RPD 13
validateRpd13s1();
validateRpd13s2();
validateRpd13s3();
validateRpd13s4();
validateRpd13s5();
validateRpd13s6();
validateRpd13s7();
validateRpd13s8();
validateRpd13s9();
validateRpd13s10();
validateRpd13s11();
validateRpd13s12();
validateRpd13s13();
validateRpd13s14();
validateRpd13s15();
validateRpd13s16();
validateRpd13s17();
validateRpd13s18();
// RPD 14
validateRpd14s1();
// RPD 15
validateRpd15s1();
validateRpd15s2();
validateRpd15s3();
validateRpd15s4();
validateRpd15s5();
validateRpd15s6();
validateRpd15s7();
// RPD 16
validateRpd16s1();
validateRpd16s2();
validateRpd16s3();
validateRpd16s4();
// RPD 18
validateRpd18s1();
validateRpd18s2();
// RPD 22
validateRpd22s1();
validateRpd22s2();
validateRpd22s3();
validateRpd22s4();
validateRpd22s5();
validateRpd22s6();
validateRpd22s7();
validateRpd22s8();
validateRpd22s9();
validateRpd22s10();
}
/**
* Keep structure and design separate as much as possible: use HTML or XHTML for the structure of the site and CSS
* for its design.
*/
public void validateRpd1s1()
{
// HTML Validation errors are checked by XHTMLValidator.
}
/**
* Build websites according to the "layered construction" principle.
*/
public void validateRpd1s2()
{
// This guideline cannot be automatically tested.
}
/**
* Do not make the function of the website dependent on optional technology, such as CSS and client-side script:
* optional technology should complement the information on the site and its use, and should not interfere with
* access to it if this technology is not supported.
*/
public void validateRpd1s3()
{
// Links validation.
Elements linkElements = getElements("a");
// Links must not use javascript in href.
for (String hrefValue : getAttributeValues(linkElements, "href")) {
assertFalse(Type.ERROR, "rpd1s3.javascript", hrefValue.startsWith("javascript:"));
}
// Links must not use the attributes listed below.
List<String> forbiddenAttributes =
Arrays.asList(ATTR_BLUR, ATTR_CHANGE, ATTR_CLICK, ATTR_FOCUS, ATTR_LOAD, ATTR_MOUSEOVER, ATTR_SELECT,
ATTR_SELECT, ATTR_UNLOAD);
for (Element linkElement : linkElements) {
if (!ListUtils.intersection(getAttributeNames(linkElement), forbiddenAttributes).isEmpty()) {
assertFalse(Type.ERROR, "rpd1s3.inlineEventHandlers", getAttributeValue(linkElement, ATTR_HREF).equals(
"")
|| getAttributeValue(linkElement, ATTR_HREF).equals("
}
}
validateRpd1s3AboutForms();
}
private void validateRpd1s3AboutForms()
{
// Form validation
Elements formElements = getElements("form");
for (Element formElement : formElements) {
// Look for either a submit input or an image input with the 'alt' attribute specified.
// See http://www.w3.org/TR/WCAG10-HTML-TECHS/#forms-graphical-buttons
boolean hasSubmit = false;
boolean hasButtonSubmit = false;
for (Element input : formElement.getElementsByTag(ELEM_INPUT)) {
String type = input.attr(ATTR_TYPE);
if (SUBMIT.equals(type) || (IMAGE.equals(type) && !StringUtils.isEmpty(input.attr(ATTR_ALT)))) {
hasSubmit = true;
break;
}
}
for (Element button : formElement.getElementsByTag("button")) {
if (!button.hasAttr(ATTR_TYPE) || SUBMIT.equals(button.attr(ATTR_TYPE))) {
hasButtonSubmit = true;
break;
}
}
assertTrue(Type.ERROR, "rpd1s3.formSubmit", hasSubmit || hasButtonSubmit);
}
}
/**
* Use HTML 4.01 or XHTML 1.0 according to the W3C specifications for the markup of websites.
*/
public void validateRpd2s1()
{
// HTML Validation errors are checked by XHTMLValidator.
}
/**
* Do not use any markup which is referred to as deprecated (outmoded) in the W3C specifications.
*/
public void validateRpd2s2()
{
// HTML Validation errors are checked by XHTMLValidator.
}
/**
* When modifying an existing website: only use the Transitional version of HTML 4.01 or XHTML 1.0 if it is not
* possible or desirable to use the Strict version.
*/
public void validateRpd2s3()
{
// No DOCTYPE in HTML5
}
/**
* When building a new website: only use the Strict version of HTML 4.01 or XHTML 1.0.
*/
public void validateRpd2s4()
{
// No DOCTYPE in HTML5
}
/**
* Do not use frames on websites. Therefore, also do not use the Frameset version of HTML 4.01 or XHTML 1.0.
*/
public void validateRpd2s5()
{
// JSoup does not handle <frame> tags
}
/**
* Use CSS Level-2.1 according to the W3C specification for designing websites.
*/
public void validateRpd2s6()
{
// CSS Validation errors are checked by CSSValidator.
}
/**
* If client-side script is used, use ECMAScript according to the specification.
*/
public void validateRpd2s7()
{
// This guideline cannot be automatically tested.
}
/**
* If elements in the HTML hierarchy are to be manipulated, use the W3C DOM according to the specification.
*/
public void validateRpd2s8()
{
// This guideline cannot be automatically tested.
}
/**
* Build a website according to the Web Content Accessibility Guidelines (WCAG 1.0) of the W3C.
*/
public void validateRpd2s9()
{
// This guideline cannot be automatically tested.
}
/**
* Write both grammatically correct and descriptive markup.
*/
public void validateRpd3s1()
{
// <b> and <i> are not allowed.
assertFalse(Type.ERROR, "rpd3s1.boldMarkup", containsElement("b"));
assertFalse(Type.ERROR, "rpd3s1.italicMarkup", containsElement("i"));
}
/**
* Use markup for headings that express the hierarchy of information on the page.
*/
public void validateRpd3s2()
{
Elements h1s = getElements(ELEM_H1);
// A page must contain at least a h1.
assertTrue(Type.ERROR, "rpd3s2.noheading", !h1s.isEmpty());
// It is recommended to use only one h1 per page.
if (h1s.size() > 1) {
addError(Type.WARNING, -1, -1, "rpd3s2.multipleh1");
}
}
/**
* Do not skip any levels in the hierarchy of headings in the markup.
*/
public void validateRpd3s3()
{
List<String> headings = Arrays.asList("//h1", "h2", "h3", "h4", "h5", "h6");
int previousLevel = 1;
for (Element element : getElements(headings)) {
int currentLevel = Integer.parseInt(element.nodeName().substring(1));
// Verify that we haven't jumped from h1 to h3.
assertTrue(Type.ERROR, "rpd3s3.headings", currentLevel <= previousLevel + 1);
previousLevel = currentLevel;
}
}
/**
* Use the p (paragraph) element to indicate paragraphs. Do not use the br (linebreak) element to separate
* paragraphs.
*/
public void validateRpd3s4()
{
Pattern pattern = Pattern.compile("<br(\\s)*(/)?>(\\s)*<br(\\s)*(/)?>");
for (Element br : getElements(ELEM_BR)) {
Matcher matcher = pattern.matcher(br.parent().html());
assertFalse(Type.ERROR, "rpd3s4.linebreaks", matcher.find());
}
}
/**
* Use the em (emphasis) and strong elements to indicate emphasis.
*/
public void validateRpd3s5()
{
// <b> and <i> are not allowed.
String key = "rpd3s5.invalidMarkup";
assertFalse(Type.ERROR, key, containsElement(ELEM_BOLD));
assertFalse(Type.ERROR, key, containsElement(ELEM_ITALIC));
}
/**
* Use the abbr (abbreviation) element for an abbreviation if confusion could arise concerning its meaning, if the
* abbreviation plays a very important role in the text or if the abbreviation is not listed in the Dutch
* dictionary.
*/
public void validateRpd3s6()
{
// This guideline cannot be automatically tested.
}
/**
* Use the dfn (definition) element to indicate terms that are defined elsewhere in a definition list.
*/
public void validateRpd3s7()
{
// This guideline cannot be automatically tested.
}
/**
* Use the ins (insertion) and del (deletion) elements to indicate regular changes in the content of a page.
*/
public void validateRpd3s8()
{
// This guideline cannot be automatically tested.
}
/**
* Avoid using the sup (superscript) and sub (subscript) element if possible.
*/
public void validateRpd3s9()
{
// <sub> and <sup> are not allowed.
assertFalse(Type.ERROR, "rpd3s9.sub", containsElement("sub"));
assertFalse(Type.ERROR, "rpd3s9.sup", containsElement("sup"));
}
/**
* Use the cite element for references to people and titles.
*/
public void validateRpd3s10()
{
// This guideline cannot be automatically tested.
}
/**
* Avoid using the q (quotation) element.
*/
public void validateRpd3s11()
{
// <q> is not allowed.
assertFalse(Type.ERROR, "rpd3s11.quotation", containsElement("q"));
}
/**
* Use the blockquote element to indicate (long) quotations.
*/
public void validateRpd3s12()
{
// This guideline cannot be automatically tested.
}
/**
* Use ol (ordered list) and ul (unordered list) elements to indicate lists.
*/
public void validateRpd3s13()
{
//ToDo: difficult to do with JSoup
}
/**
* Use the dl (definition list), the dt (definition term) and dd (definition data) elements to indicate lists with
* definitions.
*/
public void validateRpd3s14()
{
// This guideline cannot be automatically tested.
}
/**
* Give meaningful names to id and class attributes.
*/
public void validateRpd3s15()
{
// This guideline cannot be automatically tested.
}
/**
* Create unique, unchanging URLs.
*/
public void validateRpd4s1()
{
// URL guidelines can't be automatically tested, this validator allow to validate content only.
}
/**
* Dynamically generated URLs should continue to refer to the same content if content is changed or added.
*/
public void validateRpd4s2()
{
// URL guidelines can't be automatically tested, this validator allow to validate content only.
}
/**
* Avoid using sessions in URLs.
*/
public void validateRpd4s3()
{
// URL guidelines can't be automatically tested, this validator allow to validate content only.
}
/**
* Provide redirection to the new location if information is moved.
*/
public void validateRpd4s4()
{
// URL guidelines can't be automatically tested, this validator allow to validate content only.
}
/**
* Automatic redirection should be carried by the server if possible.
*/
public void validateRpd4s5()
{
// URL guidelines can't be automatically tested, this validator allow to validate content only.
}
/**
* Use friendly URLs that are readable and recognizable.
*/
public void validateRpd4s6()
{
// URL guidelines can't be automatically tested, this validator allow to validate content only.
}
/**
* Set up a readable, expandable directory structure.
*/
public void validateRpd4s7()
{
// URL guidelines can't be automatically tested, this validator allow to validate content only.
}
/**
* In the event that important information is provided through a closed standard, the same information should also
* be provided through an open standard.
*/
public void validateRpd5s1()
{
// This guideline cannot be automatically tested.
}
/**
* Each HTML or HTML5 document must begin with a valid doctype declaration.
* Is considered valid a doctype with "html" name and no attribute.
*/
public void validateRpd6s1()
{
boolean validDocumentType = false;
for (Node node : this.html5Document.childNodes()) {
if (node instanceof DocumentType) {
DocumentType documentType = (DocumentType) node;
validDocumentType = "html".equalsIgnoreCase(documentType.attr("name")) && StringUtils
.isAllEmpty(documentType.attr("publicId"), documentType.attr("systemId"));
break;
}
}
assertTrue(Type.ERROR, "rpd6s1.doctype", validDocumentType);
}
/**
* Put the content of the page in the HTML source code in order of importance.
*/
public void validateRpd6s2()
{
// This guideline cannot be automatically tested.
}
/**
* The alt (alternative) attribute should be used on every img (image) and area element and should be provided with
* an effective alternative text.
*/
public void validateRpd7s1()
{
// alt attributes are mandatory in <img>
for (Element img : getElements(ELEM_IMG)) {
assertTrue(Type.ERROR, "rpd7s1.img", hasAttribute(img, ATTR_ALT));
}
// alt attributes are mandatory in <area>
for (Element area : getElements(ELEM_AREA)) {
assertTrue(Type.ERROR, "rpd7s1.area", hasAttribute(area, ATTR_ALT));
}
// alt attributes are mandatory in <input type="image">
for (Element input : getElements(ELEM_INPUT)) {
if (getAttributeValue(input, ATTR_TYPE).equals(IMAGE)) {
assertTrue(Type.ERROR, "rpd7s1.input", hasAttribute(input, ATTR_ALT));
}
}
}
/**
* Do not use an alt attribute to display tooltips.
*/
public void validateRpd7s2()
{
// This guideline cannot be automatically tested.
}
/**
* Do not use d-links on websites. Use of the longdesc (long description) attribute is preferred if the text
* alternative on the alt attribute is inadequate for understanding the information in the image.
*/
public void validateRpd7s3()
{
// This guideline cannot be automatically tested.
}
/**
* Images placed in a link should have a non-empty text alternative to enable visitors who do not see the image to
* follow the link.
*/
public void validateRpd7s4()
{
for (Element link : getElements(ELEM_LINK)) {
// Look for images in the link.
boolean hasNonEmptyAlt = false;
for (Element child : getChildren(link, ELEM_IMG)) {
if (StringUtils.isNotEmpty(getAttributeValue(child, ATTR_ALT))) {
hasNonEmptyAlt = true;
}
}
// Look for text in the link.
boolean hasText = false;
for (Element linkChild : link.getAllElements()) {
if (linkChild.hasText()) {
hasText = true;
}
}
// Images in links must have a not empty alt attribute if there's no text in the link.
assertTrue(Type.ERROR, "rpd7s4.links", hasNonEmptyAlt || hasText);
}
}
/**
* When using image maps, indicate an effective text alternative for both the img element and each area element by
* means of the alt attribute.
*/
public void validateRpd7s5()
{
// Non-empty alt attributes are mandatory in <img usemap=''>
for (Element img : getElements(ELEM_IMG)) {
if (hasAttribute(img, "usemap")) {
assertFalse(Type.ERROR, "rpd7s5.img", StringUtils.isEmpty(getAttributeValue(img, ATTR_ALT)));
}
}
// Non-empty alt attributes are mandatory in <area>
for (Element area : getElements(ELEM_AREA)) {
assertFalse(Type.ERROR, "rpd7s5.area", StringUtils.isEmpty(getAttributeValue(area, ATTR_ALT)));
}
}
/**
* Decorative images should be inserted via CSS as much as possible. Informative images should be inserted via HTML.
*/
public void validateRpd7s6()
{
// This guideline cannot be automatically tested.
}
/**
* Applying CSS Image Replacement techniques to essential information is not recommended.
*/
public void validateRpd7s7()
{
// This guideline cannot be automatically tested.
}
/**
* Do not describe the mechanism behind following a link.
*/
public void validateRpd8s1()
{
List<String> forbiddenLinkTexts = Arrays.asList(messages.getString("rpd8s1.forbiddenLinkTexts").split(","));
for (Element link : getElements(ELEM_LINK)) {
for (Element linkChild : link.getAllElements()) {
if (linkChild.hasText()) {
for (String forbiddenLinkText : forbiddenLinkTexts) {
assertFalse(Type.ERROR, "rpd8s1.link", StringUtils.containsIgnoreCase(linkChild.text(),
forbiddenLinkText));
}
}
}
}
}
/**
* Write clear, descriptive text for links.
*/
public void validateRpd8s2()
{
// This guideline cannot be automatically tested.
}
/**
* Use the minimum amount of text needed to understand where the link leads.
*/
public void validateRpd8s3()
{
// This guideline cannot be automatically tested.
}
/**
* Provide sufficient information on the destination of a link to prevent unpleasant surprises for the visitor.
*/
public void validateRpd8s4()
{
// This guideline cannot be automatically tested.
}
/**
* When using client-side script in combination with a link: make the script functionality an expansion of the basic
* functionality of the link.
*/
public void validateRpd8s5()
{
// Already checked by RPD 1s3
}
/**
* When using client-side script in combination with a link: if the link does not lead to anything, do not confront
* the visitor without support for client-side script with a non-working link.
*/
public void validateRpd8s6()
{
// Already checked by RPD 1s3
}
/**
* When using client-side script in combination with a link: if necessary, use client-side script as an expansion of
* server-side functions.
*/
public void validateRpd8s7()
{
// This guideline cannot be automatically tested.
}
/**
* Links must be easy to distinguish from other text.
*/
public void validateRpd8s8()
{
// This guideline cannot be automatically tested.
}
/**
* Provide a logical order for the links on the page. Use the tabindex attribute to deviate from the standard tab
* order for links if this order is inadequate for correct use of the page by keyboard users.
*/
public void validateRpd8s9()
{
// This guideline cannot be automatically tested.
}
/**
* Do not make it impossible to tab to links. Do not remove the focus rectangle surrounding a link or the
* possibility of focusing on a link.
*/
public void validateRpd8s10()
{
// This guideline cannot be automatically tested.
}
/**
* Avoid using the Access key attribute. If the decision is nevertheless made to apply this attribute, only use it
* on links that remain unchanged throughout the site (e.g. main navigation) and limit the shortcut key combinations
* to numbers.
*/
public void validateRpd8s11()
{
for (Element link : getElements(ELEM_LINK)) {
if (hasAttribute(link, ATTR_ACCESSKEY)) {
assertTrue(Type.ERROR, "rpd8s11.accesskey", StringUtils.isNumeric(getAttributeValue(link,
ATTR_ACCESSKEY)));
}
}
}
/**
* Give blind visitors additional options to skip long lists of links.
*/
public void validateRpd8s12()
{
// This guideline cannot be automatically tested.
}
/**
* At the top of pages with many topics, provide a page index with links to navigate to the different topics.
*/
public void validateRpd8s13()
{
// This guideline cannot be automatically tested.
}
/**
* Links on websites should not automatically open new windows without warning.
*/
public void validateRpd8s14()
{
for (Element link : getElements(ELEM_LINK)) {
// target attribute is forbidden
assertFalse(Type.ERROR, "rpd8s14.target", hasAttribute(link, "target"));
if (hasAttribute(link, ATTR_CLICK)) {
// Usage of window.open is forbidden
assertFalse(Type.ERROR, "rpd8s14.window", getAttributeValue(link, ATTR_CLICK).contains("window.open"));
}
}
}
/**
* Do not open any new windows automatically, unless the location of the link contains useful information that may
* be necessary during an important uninterruptible process.
*/
public void validateRpd8s15()
{
// This guideline cannot be automatically tested.
}
/**
* Links to e-mail addresses: the e-mail address to which the message is addressed must be visible in the link text.
*/
public void validateRpd8s16()
{
for (Element link : getElements(ELEM_LINK)) {
String href = getAttributeValue(link, ATTR_HREF);
if (href != null && href.startsWith(MAILTO)) {
String email = StringUtils.substringAfter(href, MAILTO);
if (email.contains(QUERY_STRING_SEPARATOR)) {
email = StringUtils.substringBefore(email, QUERY_STRING_SEPARATOR);
}
assertTrue(Type.ERROR, "rpd8s16.email", link.text().contains(email));
}
}
}
/**
* Links to e-mail addresses: the URL in the href attribute of a link to an e-mail address may only contain the
* mailto protocol and an e-mail address.
*/
public void validateRpd8s17()
{
for (Element link : getElements(ELEM_LINK)) {
String href = getAttributeValue(link, ATTR_HREF);
if (href != null && href.startsWith(MAILTO)) {
String email = StringUtils.substringAfter(href, MAILTO);
assertTrue(Type.ERROR, "rpd8s17.email", email
.matches("^[\\w\\-]([\\.\\w])+[\\w]+@([\\w\\-]+\\.)+[a-zA-Z]{2,4}$"));
}
}
}
/**
* Do not apply any technical measures to the website to hide an e-mail address from spam robots.
*/
public void validateRpd8s18()
{
// This guideline cannot be automatically tested.
}
/**
* Be extremely cautious when publishing e-mail addresses of visitors to the website. Inform the visitor of which
* information will be published on the site, or do not publish the visitor's e-mail address.
*/
public void validateRpd8s19()
{
// This guideline cannot be automatically tested.
}
/**
* When presenting downloadable files, inform the visitor how to download and then use them.
*/
public void validateRpd8s20()
{
// This guideline cannot be automatically tested.
}
/**
* Serve files with the correct MIME type.
*/
public void validateRpd8s21()
{
// This guideline cannot be automatically tested.
}
/**
* Do not automatically open links to downloadable files in a new window.
*/
public void validateRpd8s22()
{
// Duplicate of 8s14
}
/**
* Do not intentionally serve downloadable files with an unknown or incorrect MIME type to force the browser to do
* something.
*/
public void validateRpd8s23()
{
// This guideline cannot be automatically tested.
}
/**
* CSS should be placed in linked files and not mixed with the HTML source code.
*/
public void validateRpd9s1()
{
assertFalse(Type.ERROR, "rpd9s1.attr", getElement(ELEM_BODY).getElementsByAttribute(STYLE).isEmpty());
assertFalse(Type.ERROR, "rpd9s1.tag", getElement(ELEM_BODY).getElementsByTag(STYLE).isEmpty());
}
/**
* Pages should remain usable if a web browser does not support CSS.
*/
public void validateRpd9s2()
{
// This guideline cannot be automatically tested.
}
/**
* Make sure that the meaning of communicative elements is not expressed only through colour.
*/
public void validateRpd10s1()
{
// This guideline cannot be automatically tested.
}
/**
* Be consistent with colour use when indicating meaning.
*/
public void validateRpd10s2()
{
// This guideline cannot be automatically tested.
}
/**
* Make sure there is sufficient brightness contrast between the text and the background colour.
*/
public void validateRpd10s3()
{
// This guideline cannot be automatically tested.
}
/**
* Use tables to display relational information and do not use them for layout.
*/
public void validateRpd11s1()
{
// This guideline cannot be automatically tested.
}
/**
* Use the th (table header) to describe a column or row in a table with relational information.
*/
public void validateRpd11s2()
{
for (Element table : getElements(ELEM_TABLE)) {
assertTrue(Type.ERROR, "rpd11s2.th", getChildrenTagNames(table).contains(ELEM_TH));
}
}
/**
* Group rows with only th (table header) cells with the thead (table head) element. Group the rest of the table
* with the tbody (table body) element.
*/
public void validateRpd11s3()
{
// This guideline cannot be automatically tested.
}
/**
* @param table Table to analyze
* @return true if the table contains th with ids and td
*/
private boolean hasTableHeadersAndIds(Element table)
{
for (Element td : table.getElementsByTag("td")) {
if (!td.hasAttr("headers")) {
return false;
}
}
for (Element td : table.getElementsByTag("th")) {
if (!td.hasAttr("id")) {
return false;
}
}
return true;
}
/**
* Use the scope attribute to associate table labels (th cells) with columns or rows.
*/
public void validateRpd11s4()
{
for (Element table : getElements(ELEM_TABLE)) {
boolean hasHeadersAndIds = hasTableHeadersAndIds(table);
if (!hasHeadersAndIds) {
for (Element th : getChildren(table, ELEM_TH)) {
assertTrue(Type.ERROR, "rpd11s4.scope", hasAttribute(th, ATTR_SCOPE));
}
}
}
}
/**
* Use the headers and id attributes to associate table labels (th cells) with individual cells in complex tables.
*/
public void validateRpd11s5()
{
for (Element table : getElements(ELEM_TABLE)) {
boolean hasScope = false;
for (Element th : getChildren(table, ELEM_TH)) {
if (hasAttribute(th, ATTR_SCOPE)) {
hasScope = true;
}
}
if (!hasScope) {
assertTrue(Type.ERROR, "rpd11s5.headers", hasTableHeadersAndIds(table));
}
}
}
/**
* Provide abbreviations for table labels (th cells) by means of the abbr (abbreviation) attribute if the content of
* the table label is so long that repetition in a speech browser could cause irritation.
*/
public void validateRpd11s6()
{
// This guideline cannot be automatically tested.
}
/**
* Use the caption element or heading markup to provide a heading above a table.
*/
public void validateRpd11s7()
{
// This guideline cannot be automatically tested.
}
/**
* When modifying an existing website: use CSS for the presentation and layout of web pages, and avoid using tables
* for layout.
*/
public void validateRpd11s8()
{
// This guideline cannot be automatically tested.
}
/**
* When using tables for layout: do not use more than one table and use CSS for the design of this table as much as
* possible.
*/
public void validateRpd11s9()
{
// This guideline cannot be automatically tested.
}
/**
* When using tables for layout: do not apply any accessibility markup.
*/
public void validateRpd11s10()
{
// This guideline cannot be automatically tested.
}
/**
* Do not use frames on websites. This applies to regular frames in framesets as well as iframes.
*/
public void validateRpd12s1()
{
// Usage of iframes is forbidden
// frameset and frame tags are checked in RPD2.5.
assertFalse(Type.ERROR, "rpd12s1.iframe", containsElement(ELEM_IFRAME));
}
/**
* Use the label element to explicitly associate text with an input field in a form.
*/
public void validateRpd13s1()
{
String message = "rpd13s1.label";
// type = text|password|checkbox|radio|submit|reset|file|hidden|image|button
List<String> inputWithoutLabels = Arrays.asList(SUBMIT, RESET, IMAGE, BUTTON, HIDDEN);
for (Element input : getElements(ELEM_INPUT)) {
// Some inputs doesn't need a label.
if (!inputWithoutLabels.contains(getAttributeValue(input, ATTR_TYPE))) {
// Labelled inputs must have an ID.
String id = getAttributeValue(input, ATTR_ID);
assertFalse(Type.ERROR, message, id == null);
if (id != null) {
// Looking for the label associated to the input.
boolean hasLabel = false;
for (Element label : getElement(ELEM_BODY).getElementsByTag("label")) {
if (id.equals(label.attr("for"))) {
hasLabel = true;
break;
}
}
assertTrue(Type.ERROR, message, hasLabel);
}
}
}
}
/**
* Use the tabindex attribute to deviate from the standard tab order on form fields if this order is inadequate for
* correct use of the form by keyboard users.
*/
public void validateRpd13s2()
{
// This guideline cannot be automatically tested.
}
/**
* Apply grouping of input fields by means of the fieldset element.
*/
public void validateRpd13s3()
{
// Display a warning if a form without fieldset is present.
for (Element form : getElements(ELEM_FORM)) {
if (!getChildrenTagNames(form).contains(ELEM_FIELDSET)) {
addError(Type.WARNING, -1, -1, "rpd13s3.fieldset");
}
}
}
/**
* Avoid automatic redirection during interaction with forms.
*/
public void validateRpd13s4()
{
for (Element form : getElements(ELEM_FORM)) {
boolean hasSubmit = false;
boolean hasDynamicSelect = false;
for (Element input : form.getElementsByTag(ELEM_INPUT)) {
String type = input.attr(ATTR_TYPE);
if ("submit".equals(type) || "image".equals(type)) {
hasSubmit = true;
break;
}
}
assertTrue(Type.ERROR, "rpd13s4.submit", hasSubmit);
for (Element select : form.getElementsByTag("select")) {
if (select.hasAttr("onchange")) {
hasDynamicSelect = true;
break;
}
}
if (hasDynamicSelect) {
addError(Type.WARNING, -1, -1, "rpd13s4.select");
}
}
}
/**
* Do not use client-side script or forms as the only way of accessing information on the site.
*/
public void validateRpd13s5()
{
for (Element form : getElements(ELEM_FORM)) {
// Display a warning if the form has a "onsubmit" event handler.
if (hasAttribute(form, ATTR_SUBMIT)) {
addError(Type.WARNING, -1, -1, "rpd13s5.onsubmit");
}
// Display a warning if the form has a "onchange" event handler.
if (hasAttribute(form, ATTR_CHANGE)) {
addError(Type.WARNING, -1, -1, "rpd13s5.onchange");
}
}
}
/**
* Do not confront a visitor with a non-working form if optional technologies "such as CSS or client-side script"
* are not supported by the browser.
*/
public void validateRpd13s6()
{
// This guideline cannot be automatically tested.
}
/**
* Use CSS sparingly for input fields and form buttons.
*/
public void validateRpd13s7()
{
// This guideline cannot be automatically tested.
}
/**
* If a visitor has to provide personal data, let him know what will be done with this data, e.g. in the form of a
* privacy statement.
*/
public void validateRpd13s8()
{
// This guideline cannot be automatically tested.
}
/**
* Do not ask a visitor to provide more information by means of a form than necessary for the purpose of the form.
* Keep forms as short as possible and limit the mandatory completion of form fields.
*/
public void validateRpd13s9()
{
// This guideline cannot be automatically tested.
}
/**
* Indicate which fields are mandatory and which are optional.
*/
public void validateRpd13s10()
{
// This guideline cannot be automatically tested.
}
/**
* Provide alternate contact options, such as address details, telephone number or e-mail addresses, if available.
*/
public void validateRpd13s11()
{
// This guideline cannot be automatically tested.
}
/**
* Let the visitor know what will be done with the form when it is sent.
*/
public void validateRpd13s12()
{
// This guideline cannot be automatically tested.
}
/**
* Give the visitor the option of saving his reply.
*/
public void validateRpd13s13()
{
// This guideline cannot be automatically tested.
}
/**
* Once the visitor has completed and sent the form, send him confirmation that his message has been received by the
* recipient (autoreply).
*/
public void validateRpd13s14()
{
// This guideline cannot be automatically tested.
}
/**
* Before displaying complex forms, give the visitor an impression of the size of the form.
*/
public void validateRpd13s15()
{
// This guideline cannot be automatically tested.
}
/**
* List documents which the visitor might need while completing the form beforehand.
*/
public void validateRpd13s16()
{
// This guideline cannot be automatically tested.
}
/**
* Provide forms with instructions for the visitor if necessary, particularly for the applicable input fields.
*/
public void validateRpd13s17()
{
// This guideline cannot be automatically tested.
}
/**
* Do not add any reset buttons to forms.
*/
public void validateRpd13s18()
{
String exprString = "//input[@type='reset']";
boolean hasResetForm = false;
for (Element input : getElement(ELEM_BODY).getElementsByTag(ELEM_INPUT)) {
if ("reset".equals(input.attr(ATTR_TYPE))) {
hasResetForm = true;
break;
}
}
assertFalse(Type.ERROR, "rpd13s18.reset", hasResetForm);
}
/**
* Do not use client-side script for essential functionality on web pages, unless any lack of support for these
* scripts is sufficiently compensated by HTML alternatives and/or server-side script.
*/
public void validateRpd14s1()
{
// This guideline cannot be automatically tested.
}
/**
* The visitor should have the option of choosing between languages on every page of the site.
*/
public void validateRpd15s1()
{
// This guideline cannot be automatically tested.
}
/**
* Links for language choice should have a clear and consistent place in the navigation of the site.
*/
public void validateRpd15s2()
{
// This guideline cannot be automatically tested.
}
/**
* Use fully written out (textual) links to the language versions.
*/
public void validateRpd15s3()
{
// This guideline cannot be automatically tested.
}
/**
* Write links to language versions in their corresponding languages.
*/
public void validateRpd15s4()
{
// This guideline cannot be automatically tested.
}
/**
* Do not use associations with nationalities for language choice.
*/
public void validateRpd15s5()
{
// This guideline cannot be automatically tested.
}
/**
* Specify the base language of a page in the markup.
*/
public void validateRpd15s6()
{
Element html = getElement(ELEM_HTML);
// Check for lang attribute in th html node.
assertTrue(Type.ERROR, "rpd15s6.lang", html != null && hasAttribute(html, "lang"));
}
/**
* Indicate language variations in the content of pages in the markup.
*/
public void validateRpd15s7()
{
// This guideline cannot be automatically tested.
}
private String getMetaCharset()
{
Elements metas = this.html5Document.getElementsByAttributeValue("http-equiv", "Content-Type");
for (Element meta : metas) {
if ("meta".equals(meta.tagName())) {
return meta.attr("content");
}
}
return null;
}
/**
* Specify the character set for web pages.
*/
public void validateRpd16s1()
{
String charset = getMetaCharset();
assertTrue(Type.ERROR, "rpd16s1.nometa", charset != null);
assertTrue(Type.ERROR, "rpd16s1.charset", StringUtils.containsIgnoreCase(charset, CONTENT_CHARSET_FRAGMENT));
}
/**
* Specify the UTF-8 character set.
*/
public void validateRpd16s2()
{
String charset = getMetaCharset();
assertTrue(Type.ERROR, "rpd16s2.nometa", charset != null);
assertTrue(Type.ERROR, "rpd16s2.notutf8", StringUtils.containsIgnoreCase(charset, "charset=utf-8"));
}
/**
* Also specify the character set by means of HTTP headers, if possible.
*/
public void validateRpd16s3()
{
// This guideline cannot be automatically tested.
}
/**
* Use (at least) the meta element to specify the character set and place this element as high as possible in the
* head section of the markup.
*/
public void validateRpd16s4()
{
Element meta = getElement(ELEM_META);
assertTrue(Type.ERROR, "rpd16s4.position", hasAttribute(meta, ATTR_CONTENT)
&& StringUtils.containsIgnoreCase(getAttributeValue(meta, ATTR_CONTENT), CONTENT_CHARSET_FRAGMENT));
}
/**
* Use a unique, descriptive title for each page.
*/
public void validateRpd18s1()
{
// This guideline cannot be automatically tested.
}
/**
* Write short, concise text, in which the main message is mentioned at the top of the page.
*/
public void validateRpd18s2()
{
// This guideline cannot be automatically tested.
}
/**
* Use language that the visitor understands: limit the use of jargon, difficult terms and abbreviations.
*/
public void validateRpd22s1()
{
// This guideline cannot be automatically tested.
}
/**
* Give visitors an <em>escape route</em>: possibilities to continue if they get stuck. Escape routes include useful
* links, being able to use the back button, a search function, and being able to correct input errors immediately.
*/
public void validateRpd22s2()
{
// This guideline cannot be automatically tested.
}
/**
* Don't make visitors guess: provide information on how they can correct errors they have made. Take into account
* the most common errors.
*/
public void validateRpd22s3()
{
// This guideline cannot be automatically tested.
}
/**
* Make modified error pages "for errors such as dead links (404 Not Found)" where the visitor is given options for
* continuing within the site.
*/
public void validateRpd22s4()
{
// This guideline cannot be automatically tested.
}
/**
* In the event of an error message as a result of sending a form, give the visitor the option of correcting the
* error in the form immediately and don't make him be dependent on the use of the back button.
*/
public void validateRpd22s5()
{
// This guideline cannot be automatically tested.
}
/**
* When implementing a search engine on the website: use "smart" search technology that takes into account spelling
* errors, similar search terms, terms in singular or plural form, etc.
*/
public void validateRpd22s6()
{
// This guideline cannot be automatically tested.
}
/**
* Provide a well-organised list of the most relevant search results. If too many search results are provided, it
* takes visitors too long to find the desired information. Give visitors the option of entering search criteria, or
* sorting the search results.
*/
public void validateRpd22s7()
{
// This guideline cannot be automatically tested.
}
/**
* Give visitors the option of reporting errors on the site.
*/
public void validateRpd22s8()
{
// This guideline cannot be automatically tested.
}
/**
* Use colours, icons and textual explanations to draw the visitor's attention to an error message and explain the
* problem.
*/
public void validateRpd22s9()
{
// This guideline cannot be automatically tested.
}
/**
* Give visitors the option of finding information in alternate ways. For example, by providing a sitemap, search
* functions, or by means of a request by e-mail, letter or telephone.
*/
public void validateRpd22s10()
{
// This guideline cannot be automatically tested.
}
}
|
package eu.bcvsolutions.idm.core.model.service.impl;
import java.io.Serializable;
import java.text.MessageFormat;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.UUID;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import org.joda.time.DateTime;
import org.modelmapper.PropertyMap;
import org.modelmapper.TypeMap;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;
import org.springframework.util.ObjectUtils;
import com.google.common.base.Strings;
import com.google.common.collect.ImmutableMap;
import eu.bcvsolutions.idm.core.api.domain.ConceptRoleRequestOperation;
import eu.bcvsolutions.idm.core.api.domain.CoreResultCode;
import eu.bcvsolutions.idm.core.api.domain.Loggable;
import eu.bcvsolutions.idm.core.api.domain.RoleRequestState;
import eu.bcvsolutions.idm.core.api.dto.BaseDto;
import eu.bcvsolutions.idm.core.api.dto.IdmAutomaticRoleAttributeDto;
import eu.bcvsolutions.idm.core.api.dto.IdmConceptRoleRequestDto;
import eu.bcvsolutions.idm.core.api.dto.IdmIdentityRoleDto;
import eu.bcvsolutions.idm.core.api.dto.IdmRoleDto;
import eu.bcvsolutions.idm.core.api.dto.IdmRoleTreeNodeDto;
import eu.bcvsolutions.idm.core.api.dto.filter.IdmConceptRoleRequestFilter;
import eu.bcvsolutions.idm.core.api.exception.ForbiddenEntityException;
import eu.bcvsolutions.idm.core.api.exception.ResultCodeException;
import eu.bcvsolutions.idm.core.api.service.AbstractReadWriteDtoService;
import eu.bcvsolutions.idm.core.api.service.IdmConceptRoleRequestService;
import eu.bcvsolutions.idm.core.api.service.IdmIdentityRoleService;
import eu.bcvsolutions.idm.core.api.service.IdmRoleService;
import eu.bcvsolutions.idm.core.api.service.LookupService;
import eu.bcvsolutions.idm.core.api.service.ValueGeneratorManager;
import eu.bcvsolutions.idm.core.api.utils.DtoUtils;
import eu.bcvsolutions.idm.core.eav.api.dto.IdmFormDefinitionDto;
import eu.bcvsolutions.idm.core.eav.api.dto.IdmFormInstanceDto;
import eu.bcvsolutions.idm.core.eav.api.dto.IdmFormValueDto;
import eu.bcvsolutions.idm.core.eav.api.dto.InvalidFormAttributeDto;
import eu.bcvsolutions.idm.core.eav.api.service.FormService;
import eu.bcvsolutions.idm.core.model.entity.IdmAutomaticRole;
import eu.bcvsolutions.idm.core.model.entity.IdmAutomaticRoleAttribute;
import eu.bcvsolutions.idm.core.model.entity.IdmAutomaticRole_;
import eu.bcvsolutions.idm.core.model.entity.IdmConceptRoleRequest;
import eu.bcvsolutions.idm.core.model.entity.IdmConceptRoleRequest_;
import eu.bcvsolutions.idm.core.model.entity.IdmIdentityContract_;
import eu.bcvsolutions.idm.core.model.entity.IdmIdentityRole_;
import eu.bcvsolutions.idm.core.model.entity.IdmRoleRequest_;
import eu.bcvsolutions.idm.core.model.entity.IdmRole_;
import eu.bcvsolutions.idm.core.model.repository.IdmAutomaticRoleRepository;
import eu.bcvsolutions.idm.core.model.repository.IdmConceptRoleRequestRepository;
import eu.bcvsolutions.idm.core.security.api.domain.BasePermission;
import eu.bcvsolutions.idm.core.security.api.dto.AuthorizableType;
import eu.bcvsolutions.idm.core.workflow.model.dto.DecisionFormTypeDto;
import eu.bcvsolutions.idm.core.workflow.model.dto.WorkflowFilterDto;
import eu.bcvsolutions.idm.core.workflow.model.dto.WorkflowProcessInstanceDto;
import eu.bcvsolutions.idm.core.workflow.model.dto.WorkflowTaskInstanceDto;
import eu.bcvsolutions.idm.core.workflow.service.WorkflowProcessInstanceService;
import eu.bcvsolutions.idm.core.workflow.service.WorkflowTaskInstanceService;
@Service("conceptRoleRequestService")
public class DefaultIdmConceptRoleRequestService extends
AbstractReadWriteDtoService<IdmConceptRoleRequestDto, IdmConceptRoleRequest, IdmConceptRoleRequestFilter>
implements IdmConceptRoleRequestService {
private static final org.slf4j.Logger LOG = org.slf4j.LoggerFactory
.getLogger(DefaultIdmConceptRoleRequestService.class);
private final IdmConceptRoleRequestRepository repository;
private final WorkflowProcessInstanceService workflowProcessInstanceService;
private final LookupService lookupService;
private final IdmAutomaticRoleRepository automaticRoleRepository;
@Autowired
private WorkflowTaskInstanceService workflowTaskInstanceService;
@Autowired
private IdmRoleService roleService;
@Autowired
private FormService formService;
@Autowired
private IdmIdentityRoleService identityRoleService;
@Autowired
private ValueGeneratorManager valueGeneratorManager;
@Autowired
public DefaultIdmConceptRoleRequestService(IdmConceptRoleRequestRepository repository,
WorkflowProcessInstanceService workflowProcessInstanceService, LookupService lookupService,
IdmAutomaticRoleRepository automaticRoleRepository) {
super(repository);
Assert.notNull(workflowProcessInstanceService, "Workflow process instance service is required!");
Assert.notNull(lookupService);
Assert.notNull(automaticRoleRepository);
this.repository = repository;
this.workflowProcessInstanceService = workflowProcessInstanceService;
this.lookupService = lookupService;
this.automaticRoleRepository = automaticRoleRepository;
}
@Override
public AuthorizableType getAuthorizableType() {
// secured internally by role requests
return null;
}
@Override
public IdmConceptRoleRequest checkAccess(IdmConceptRoleRequest entity, BasePermission... permission) {
if (entity == null) {
// nothing to check
return null;
}
if (ObjectUtils.isEmpty(permission)) {
return entity;
}
// We have rights on the concept, when we have rights on whole request
if (getAuthorizationManager().evaluate(entity.getRoleRequest(), permission)) {
return entity;
}
// We have rights on the concept, when we have rights on workflow process using in the concept
String processId = entity.getWfProcessId();
if (!Strings.isNullOrEmpty(processId)) {
WorkflowProcessInstanceDto processInstance = workflowProcessInstanceService.get(processId);
if (processInstance != null) {
return entity;
}
}
throw new ForbiddenEntityException(entity.getId(), permission);
}
@Override
protected IdmConceptRoleRequestDto toDto(IdmConceptRoleRequest entity, IdmConceptRoleRequestDto dto) {
dto = super.toDto(entity, dto);
if (dto == null) {
return null;
}
// Contract from identity role has higher priority then contract ID in concept
// role
if (entity != null && entity.getIdentityRole() != null) {
dto.setIdentityContract(entity.getIdentityRole().getIdentityContract().getId());
}
// we must set automatic role to role tree node
if (entity != null && entity.getAutomaticRole() != null) {
dto.setAutomaticRole(entity.getAutomaticRole().getId());
IdmAutomaticRole automaticRole = entity.getAutomaticRole();
Map<String, BaseDto> embedded = dto.getEmbedded();
BaseDto baseDto = null;
if (automaticRole instanceof IdmAutomaticRoleAttribute) {
baseDto = lookupService.getDtoService(IdmAutomaticRoleAttributeDto.class).get(automaticRole.getId());
} else {
baseDto = lookupService.getDtoService(IdmRoleTreeNodeDto.class).get(automaticRole.getId());
}
embedded.put("roleTreeNode", baseDto); // roleTreeNode must be placed there as string, in meta model isn't
// any attribute like this
dto.setEmbedded(embedded);
}
return dto;
}
@Override
@Transactional(readOnly = true)
public IdmConceptRoleRequest toEntity(IdmConceptRoleRequestDto dto, IdmConceptRoleRequest entity) {
if (dto == null) {
return null;
}
// Set persisted value to read only properties
// TODO: Create converter for skip fields mark as read only
if (dto.getId() != null) {
IdmConceptRoleRequestDto dtoPersisited = this.get(dto.getId());
if (dto.getState() == null) {
dto.setState(dtoPersisited.getState());
}
if (dto.getLog() == null) {
dto.setLog(dtoPersisited.getLog());
}
if (dto.getWfProcessId() == null) {
dto.setWfProcessId(dtoPersisited.getWfProcessId());
}
} else {
dto.setState(RoleRequestState.CONCEPT);
}
// field automatic role exists in entity but not in dto
TypeMap<IdmConceptRoleRequestDto, IdmConceptRoleRequest> typeMap = modelMapper.getTypeMap(getDtoClass(),
getEntityClass());
if (typeMap == null) {
modelMapper.createTypeMap(getDtoClass(), getEntityClass());
typeMap = modelMapper.getTypeMap(getDtoClass(), getEntityClass());
typeMap.addMappings(new PropertyMap<IdmConceptRoleRequestDto, IdmConceptRoleRequest>() {
@Override
protected void configure() {
this.skip().setAutomaticRole(null);
}
});
}
if (entity != null) {
modelMapper.map(dto, entity);
} else {
entity = modelMapper.map(dto, getEntityClass(dto));
}
// set additional automatic role
if (entity != null) {
if (dto.getAutomaticRole() != null) {
// it isn't possible use lookupService entity lookup
IdmAutomaticRole automaticRole = automaticRoleRepository.findOne(dto.getAutomaticRole());
entity.setAutomaticRole(automaticRole);
} else {
// relation was removed
entity.setAutomaticRole(null);
}
}
return entity;
}
@Override
@Transactional
public IdmConceptRoleRequestDto cancel(IdmConceptRoleRequestDto dto) {
cancelWF(dto);
dto.setState(RoleRequestState.CANCELED);
return this.save(dto);
}
@Override
@Transactional
public IdmConceptRoleRequestDto saveInternal(IdmConceptRoleRequestDto dto) {
IdmConceptRoleRequestDto savedDto = super.saveInternal(dto);
if (dto != null && dto.getRole() != null) {
// TODO: concept role request hasn't events, after implement events for the dto, please remove this.
if (isNew(dto)) {
dto = valueGeneratorManager.generate(dto);
}
IdmRoleDto roleDto = roleService.get(dto.getRole());
if (roleDto == null) {
throw new ResultCodeException(CoreResultCode.NOT_FOUND, ImmutableMap.of("entity", dto.getRole()));
}
List<IdmFormValueDto> attributeValues = dto.getEavs().size() == 1 && dto.getEavs().get(0) != null
? dto.getEavs().get(0).getValues()
: null;
// Load sub definition by role
IdmFormDefinitionDto formDefinitionDto = roleService.getFormAttributeSubdefinition(roleDto);
if (formDefinitionDto != null) {
// Save form values for sub-definition
List<IdmFormValueDto> savedValues = formService.saveValues(savedDto, formDefinitionDto, attributeValues);
IdmFormInstanceDto formInstance = new IdmFormInstanceDto();
formInstance.setValues(savedValues);
savedDto.getEavs().clear();
savedDto.getEavs().add(formInstance);
}
}
return savedDto;
}
@Override
public void deleteInternal(IdmConceptRoleRequestDto dto) {
formService.deleteValues(dto);
this.cancelWF(dto);
super.deleteInternal(dto);
}
@Override
public IdmFormInstanceDto getRoleAttributeValues(IdmConceptRoleRequestDto dto, boolean checkChanges) {
Assert.notNull(dto);
UUID roleId = dto.getRole();
if (roleId != null) {
IdmRoleDto role = DtoUtils.getEmbedded(dto, IdmConceptRoleRequest_.role, IdmRoleDto.class, null);
if(role == null) {
role = roleService.get(roleId);
}
// Has role filled attribute definition?
UUID formDefintion = role.getIdentityRoleAttributeDefinition();
if (formDefintion != null) {
IdmFormDefinitionDto formDefinitionDto = roleService.getFormAttributeSubdefinition(role);
IdmFormInstanceDto conceptFormInstance = null;
List<IdmFormInstanceDto> eavs = dto.getEavs();
// Get form instance from given concept first
if (eavs != null && eavs.size() == 1) {
conceptFormInstance = eavs.get(0);
} else {
conceptFormInstance = formService.getFormInstance(dto, formDefinitionDto);
}
if (!checkChanges) { // Return only EAV values, without compare changes
return conceptFormInstance;
}
// If exists identity role, then we try to evaluate changes against EAVs in the
// current identity role.
ConceptRoleRequestOperation operation = dto.getOperation();
if (dto.getIdentityRole() != null && ConceptRoleRequestOperation.UPDATE == operation) {
IdmIdentityRoleDto identityRoleDto = DtoUtils.getEmbedded(dto, IdmConceptRoleRequest_.identityRole,
IdmIdentityRoleDto.class, null);
if(identityRoleDto == null) {
identityRoleDto = identityRoleService.get(dto.getIdentityRole());
}
IdmFormInstanceDto formInstance = formService.getFormInstance(identityRoleDto, formDefinitionDto);
if (formInstance != null && conceptFormInstance != null) {
List<IdmFormValueDto> conceptValues = conceptFormInstance.getValues();
List<IdmFormValueDto> values = formInstance.getValues();
conceptValues.forEach(conceptFormValue -> {
IdmFormValueDto formValue = values.stream()
.filter(value -> value.getFormAttribute()
.equals(conceptFormValue.getFormAttribute())
&& value.getSeq() == conceptFormValue.getSeq())
.findFirst()
.orElse(null);
// Compile changes
Serializable value = formValue != null ? formValue.getValue() : null;
Serializable conceptValue = conceptFormValue.getValue();
if (!Objects.equals(conceptValue, value)) {
conceptFormValue.setChanged(true);
conceptFormValue.setOriginalValue(formValue);
}
// TODO check remove in multivalued attribute
});
}
}
return conceptFormInstance;
}
}
return null;
}
@Override
protected List<Predicate> toPredicates(Root<IdmConceptRoleRequest> root, CriteriaQuery<?> query,
CriteriaBuilder builder, IdmConceptRoleRequestFilter filter) {
List<Predicate> predicates = super.toPredicates(root, query, builder, filter);
if (filter.getRoleRequestId() != null) {
predicates.add(builder.equal(root.get(IdmConceptRoleRequest_.roleRequest).get(IdmRoleRequest_.id),
filter.getRoleRequestId()));
}
if (filter.getIdentityRoleId() != null) {
predicates.add(builder.equal(root.get(IdmConceptRoleRequest_.identityRole).get(IdmIdentityRole_.id),
filter.getIdentityRoleId()));
}
if (filter.getRoleId() != null) {
predicates.add(builder.equal(root.get(IdmConceptRoleRequest_.role).get(IdmRole_.id), filter.getRoleId()));
}
if (filter.getIdentityContractId() != null) {
predicates.add(builder.equal(root.get(IdmConceptRoleRequest_.identityContract).get(IdmIdentityContract_.id),
filter.getIdentityContractId()));
}
if (filter.getAutomaticRole() != null) {
predicates.add(builder.equal(root.get(IdmConceptRoleRequest_.automaticRole).get(IdmAutomaticRole_.id),
filter.getAutomaticRole()));
}
if (filter.getOperation() != null) {
predicates.add(builder.equal(root.get(IdmConceptRoleRequest_.operation), filter.getOperation()));
}
if (filter.getState() != null) {
predicates.add(builder.equal(root.get(IdmConceptRoleRequest_.state), filter.getState()));
}
return predicates;
}
@Override
@Transactional(readOnly = true)
public List<IdmConceptRoleRequestDto> findAllByRoleRequest(UUID roleRequestId) {
return toDtos(repository.findAllByRoleRequest_Id(roleRequestId), false);
}
@Override
public List<InvalidFormAttributeDto> validateFormAttributes(IdmConceptRoleRequestDto concept) {
if(concept == null || ConceptRoleRequestOperation.REMOVE == concept.getOperation()) {
return null;
}
IdmFormInstanceDto formInstanceDto = this.getRoleAttributeValues(concept, false);
if (formInstanceDto != null) {
return formService.validate(formInstanceDto);
}
return null;
}
@Override
public void addToLog(Loggable logItem, String text) {
StringBuilder sb = new StringBuilder();
sb.append(DateTime.now());
sb.append(": ");
sb.append(text);
text = sb.toString();
logItem.addToLog(text);
LOG.info(text);
}
private void cancelWF(IdmConceptRoleRequestDto dto) {
if (!Strings.isNullOrEmpty(dto.getWfProcessId())) {
WorkflowFilterDto filter = new WorkflowFilterDto();
filter.setProcessInstanceId(dto.getWfProcessId());
@SuppressWarnings("deprecation")
Collection<WorkflowProcessInstanceDto> resources = workflowProcessInstanceService
.searchInternal(filter, false).getResources();
if (resources.isEmpty()) {
// Process with this ID not exist ... maybe was ended
this.addToLog(dto, MessageFormat.format(
"Workflow process with ID [{0}] was not deleted, because was not found. Maybe was ended before.",
dto.getWfProcessId()));
} else {
// Before delete/cancel process we try to finish process as disapprove. Cancel
// process does not trigger the parent process. That means without correct
// ending of process, parent process will be frozen!
// Find active task for this process.
WorkflowFilterDto taskFilter = new WorkflowFilterDto();
taskFilter.setProcessInstanceId(dto.getWfProcessId());
List<WorkflowTaskInstanceDto> tasks = workflowTaskInstanceService.find(taskFilter, null).getContent();
if (tasks.size() == 1) {
WorkflowTaskInstanceDto task = tasks.get(0);
DecisionFormTypeDto disapprove = task.getDecisions()
.stream()
.filter(decision -> WorkflowTaskInstanceService.WORKFLOW_DECISION_DISAPPROVE
.equals(decision.getId()))
.findFirst()
.orElse(null);
if (disapprove != null) {
// Active task exists and has decision for 'disapprove'. Complete task (process)
// with this decision.
workflowTaskInstanceService.completeTask(task.getId(), disapprove.getId(), null, null, null);
this.addToLog(dto, MessageFormat.format(
"Workflow process with ID [{0}] was disapproved, because this concept is deleted/canceled",
dto.getWfProcessId()));
return;
}
}
// We wasn't able to disapprove this process, we cancel him now.
workflowProcessInstanceService.delete(dto.getWfProcessId(),
"Role concept use this WF, was deleted. This WF was deleted too.");
this.addToLog(dto,
MessageFormat.format(
"Workflow process with ID [{0}] was deleted, because this concept is deleted/canceled",
dto.getWfProcessId()));
}
}
}
}
|
package org.csstudio.webopi;
import java.util.Optional;
import org.csstudio.opibuilder.preferences.PreferencesHelper;
import org.csstudio.opibuilder.runmode.RunModeService;
import org.csstudio.opibuilder.runmode.RunModeService.DisplayMode;
import org.csstudio.opibuilder.runmode.RunnerInput;
import org.csstudio.opibuilder.util.SingleSourceHelper;
import org.csstudio.webopi.util.RequestUtil;
import org.eclipse.core.runtime.IPath;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.osgi.util.NLS;
import org.eclipse.rap.rwt.RWT;
import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.application.IWorkbenchWindowConfigurer;
import org.eclipse.ui.application.WorkbenchWindowAdvisor;
/**
* Configures the initial size and appearance of a workbench window.
*/
public class ApplicationWorkbenchWindowAdvisor extends WorkbenchWindowAdvisor {
public ApplicationWorkbenchWindowAdvisor(IWorkbenchWindowConfigurer configurer) {
super(configurer);
}
@Override
public void postWindowCreate() {
super.postWindowCreate();
IWorkbenchWindowConfigurer configurer = getWindowConfigurer();
Shell shell = configurer.getWindow().getShell();
shell.setText("WebOPI");
shell.setMaximized(true);
RunnerInput runnerInput = RequestUtil.getOPIPathFromRequest();
if(runnerInput == null){
IPath path = null;
String s = RWT.getRequest().getServletPath();
if(s.contains(WebOPIConstants.MOBILE_SERVELET_NAME)) //$NON-NLS-1$
path = PreferencesHelper.getMobileStartupOPI();
else
path = PreferencesHelper.getStartupOPI();
if(path == null)
return;
if (path.getFileExtension().toLowerCase().equals("opi")) {
RunModeService.openDisplay(path, Optional.empty(), DisplayMode.NEW_TAB, Optional.empty());
} else {
runOther(path);
}
} else {
IPath path = runnerInput.getPath();
if (path != null) {
if (path.getFileExtension().toLowerCase().equals("opi")) {
RunModeService.openDisplay(path, Optional.ofNullable(runnerInput.getMacrosInput()), DisplayMode.NEW_TAB, Optional.empty());
} else {
runOther(path);
}
}
}
}
private void runOther(final IPath path) {
IWorkbenchPage page = PlatformUI.getWorkbench()
.getActiveWorkbenchWindow().getActivePage();
try {
SingleSourceHelper.openEditor(page, path);
} catch (Exception e) {
String message = NLS.bind("Failed to open the editor. \n {0}", e);
MessageDialog.openError(null, "Error in opening OPI", message);
}
}
public void preWindowOpen() {
IWorkbenchWindowConfigurer configurer = getWindowConfigurer();
// configurer.setShowCoolBar(!RequestUtil.isStandaloneMode());
configurer.setShowMenuBar(false);
configurer.setShowStatusLine(false);
configurer.setTitle("WebOPI");
configurer.setShellStyle(SWT.NO_TRIM);
}
}
|
package org.csstudio.sds.components.ui.internal.editparts;
import org.csstudio.platform.data.ILongValue;
import org.csstudio.platform.data.INumericMetaData;
import org.csstudio.platform.data.ISeverity;
import org.csstudio.platform.data.ITimestamp;
import org.csstudio.platform.data.IValue;
import org.csstudio.platform.data.TimestampFactory;
import org.csstudio.platform.data.ValueFactory;
import org.csstudio.platform.data.IValue.Quality;
import org.csstudio.platform.logging.CentralLogger;
import org.csstudio.platform.model.IProcessVariableWithSamples;
import org.csstudio.sds.components.model.AdvancedSliderModel;
import org.csstudio.sds.components.ui.internal.figures.AdvancedSliderFigure;
import org.csstudio.sds.ui.editparts.AbstractWidgetEditPart;
import org.csstudio.sds.ui.editparts.ExecutionMode;
import org.csstudio.sds.ui.editparts.IWidgetPropertyChangeHandler;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.draw2d.IFigure;
import org.eclipse.ui.progress.UIJob;
/**
* EditPart controller for the Slider widget. The controller mediates between
* {@link AdvancedSliderModel} and {@link AdvancedSliderFigure}.
*
* @author Sven Wende & Stefan Hofer
*
*/
public final class AdvancedSliderEditPart extends AbstractWidgetEditPart implements IProcessVariableWithSamples {
/**
* A UI job, which is used to reset the manual value of the slider figure
* after a certain amount of time.
*/
private UIJob _resetManualValueDisplayJob;
/**
* {@inheritDoc}
*/
@Override
protected IFigure doCreateFigure() {
final AdvancedSliderModel model = (AdvancedSliderModel) getWidgetModel();
final AdvancedSliderFigure slider = new AdvancedSliderFigure();
slider.addSliderListener(new AdvancedSliderFigure.ISliderListener() {
public void sliderValueChanged(final int newValue) {
if (getExecutionMode().equals(ExecutionMode.RUN_MODE)) {
model.getProperty(AdvancedSliderModel.PROP_VALUE).setManualValue(
newValue);
slider.setManualValue((Integer) newValue);
if (_resetManualValueDisplayJob == null) {
_resetManualValueDisplayJob = new UIJob("reset") {
@Override
public IStatus runInUIThread(
final IProgressMonitor monitor) {
slider.setManualValue(model.getValue());
return Status.OK_STATUS;
}
};
}
_resetManualValueDisplayJob.schedule(5000);
} else {
CentralLogger.getInstance().info(this, "Slider value changed");
}
}
});
slider.setMax(model.getMax());
slider.setMin(model.getMin());
slider.setIncrement(model.getIncrement());
slider.setValue(model.getValue());
slider.setManualValue(model.getValue());
slider.setOrientation(model.isHorizontal());
slider.setEnabled(getExecutionMode().equals(ExecutionMode.RUN_MODE) && model.isEnabled());
return slider;
}
/**
* {@inheritDoc}
*/
@Override
protected void registerPropertyChangeHandlers() {
// value
IWidgetPropertyChangeHandler valHandler = new IWidgetPropertyChangeHandler() {
public boolean handleChange(final Object oldValue,
final Object newValue,
final IFigure refreshableFigure) {
AdvancedSliderFigure slider = (AdvancedSliderFigure) refreshableFigure;
slider.setValue((Integer) newValue);
return true;
}
};
setPropertyChangeHandler(AdvancedSliderModel.PROP_VALUE, valHandler);
// min
IWidgetPropertyChangeHandler minHandler = new IWidgetPropertyChangeHandler() {
public boolean handleChange(final Object oldValue,
final Object newValue,
final IFigure refreshableFigure) {
AdvancedSliderFigure slider = (AdvancedSliderFigure) refreshableFigure;
slider.setMin((Integer) newValue);
return true;
}
};
setPropertyChangeHandler(AdvancedSliderModel.PROP_MIN, minHandler);
// max
IWidgetPropertyChangeHandler maxHandler = new IWidgetPropertyChangeHandler() {
public boolean handleChange(final Object oldValue,
final Object newValue,
final IFigure refreshableFigure) {
AdvancedSliderFigure slider = (AdvancedSliderFigure) refreshableFigure;
slider.setMax((Integer) newValue);
return true;
}
};
setPropertyChangeHandler(AdvancedSliderModel.PROP_MAX, maxHandler);
// increment
IWidgetPropertyChangeHandler incrementHandler = new IWidgetPropertyChangeHandler() {
public boolean handleChange(final Object oldValue,
final Object newValue,
final IFigure refreshableFigure) {
AdvancedSliderFigure slider = (AdvancedSliderFigure) refreshableFigure;
slider.setIncrement((Integer) newValue);
return true;
}
};
setPropertyChangeHandler(AdvancedSliderModel.PROP_INCREMENT, incrementHandler);
// orientation
IWidgetPropertyChangeHandler orientationHandler = new IWidgetPropertyChangeHandler() {
public boolean handleChange(final Object oldValue,
final Object newValue,
final IFigure refreshableFigure) {
AdvancedSliderFigure slider = (AdvancedSliderFigure) refreshableFigure;
int orientation = (Integer) newValue;
slider.setOrientation(orientation == 0);
AdvancedSliderModel model = (AdvancedSliderModel) getModel();
// invert the size of the element
model.setSize(model.getHeight(), model.getWidth());
return true;
}
};
setPropertyChangeHandler(AdvancedSliderModel.PROP_ORIENTATION,
orientationHandler);
}
/**
* {@inheritDoc}
*/
public IValue getSample(final int index) {
if (index != 0) {
throw new IndexOutOfBoundsException(index + " is not a valid sample index");
}
AdvancedSliderModel model = (AdvancedSliderModel) getWidgetModel();
int value = model.getValue();
ITimestamp timestamp = TimestampFactory.now();
// Note: the IValue implementations require a Severity, otherwise the
// format() method will throw a NullPointerException. We don't really
// have a severity here, so we fake one. This may cause problems for
// clients who rely on getting a meaningful severity from the IValue.
ISeverity severity = ValueFactory.createOKSeverity();
// Fake some metadata because it is required for an IValue.
INumericMetaData md = ValueFactory.createNumericMetaData(0, 0, 0, 0, 0,
0, 0, "");
ILongValue result = ValueFactory.createLongValue(timestamp,
severity, null, md, Quality.Original, new long[] { value });
return result;
}
/**
* {@inheritDoc}
*/
public int size() {
// always one sample
return 1;
}
}
|
package edu.ucdenver.ccp.nlp.wrapper.conceptmapper.dictionary.ncbi;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import org.apache.log4j.Logger;
import edu.ucdenver.ccp.common.collections.CollectionsUtil;
import edu.ucdenver.ccp.common.file.CharacterEncoding;
import edu.ucdenver.ccp.common.file.FileUtil;
import edu.ucdenver.ccp.common.file.FileUtil.CleanDirectory;
import edu.ucdenver.ccp.datasource.fileparsers.ncbi.gene.NcbiGeneInfoFileData;
import edu.ucdenver.ccp.datasource.fileparsers.ncbi.gene.NcbiGeneInfoFileParser;
import edu.ucdenver.ccp.datasource.identifiers.ncbi.taxonomy.NcbiTaxonomyID;
import edu.ucdenver.ccp.nlp.wrapper.conceptmapper.dictionary.ConceptMapperDictionaryBuilder;
/**
* @author Center for Computational Pharmacology, UC Denver;
* ccpsupport@ucdenver.edu
*
*/
public class NcbiGeneDictionaryFactory {
private static final Set<String> SYNONYMS_TO_IGNORE = CollectionsUtil.createSet("NEWENTRY", "hypothetical protein",
"putative");
private static final Logger logger = Logger.getLogger(NcbiGeneDictionaryFactory.class);
private static final int MINIMUM_TERM_LENGTH = 1;
/* @formatter:off */
private static final Set<NcbiTaxonomyID> MODEL_ORG_TAX_IDS = CollectionsUtil.createSet(
new NcbiTaxonomyID(3702), // Arabidopsis thaliana
new NcbiTaxonomyID(9913), // Bos taurus
new NcbiTaxonomyID(6239), // Caenorhabditis elegans
new NcbiTaxonomyID(3055), // Chlamydomonas reinhardtii
new NcbiTaxonomyID(7955), // Danio rerio
new NcbiTaxonomyID(44689), // Dictyostelium discoideum
new NcbiTaxonomyID(7227), // Drosophila melanogaster
new NcbiTaxonomyID(562), // Escherichia coli
new NcbiTaxonomyID(11103), // Hepatitis C virus
new NcbiTaxonomyID(9606), // Homo sapiens
new NcbiTaxonomyID(10090), // Mus musculus
new NcbiTaxonomyID(2104), // Mycoplasma pneumoniae
new NcbiTaxonomyID(4530), // Oryza sativa
new NcbiTaxonomyID(5833), // Plasmodium falciparum
new NcbiTaxonomyID(4754), // Pneumocystis carinii
new NcbiTaxonomyID(10116), // Rattus norvegicus
new NcbiTaxonomyID(4932), // Saccharomyces cerevisiae
new NcbiTaxonomyID(4896), // Schizosaccharomyces pombe
new NcbiTaxonomyID(31033), // Takifugu rubripes
new NcbiTaxonomyID(8355), // Xenopus laevis
new NcbiTaxonomyID(4577) // Zea mays
);
/* @formatter:on */
public static File buildModelOrganismConceptMapperDictionary(File workDirectory, CleanDirectory cleanWorkDirectory)
throws IOException {
return buildConceptMapperDictionary(workDirectory, cleanWorkDirectory, MODEL_ORG_TAX_IDS);
}
public static File buildModelOrganismConceptMapperDictionary(File geneInfoFile, File dictionaryFile,
boolean cleanDictFile) throws IOException {
return buildConceptMapperDictionary(geneInfoFile, dictionaryFile, MODEL_ORG_TAX_IDS, cleanDictFile);
}
public static File buildConceptMapperDictionary(File geneInfoFile, File dictionaryFile,
Set<NcbiTaxonomyID> taxonomyIdsToInclude, boolean cleanDictFile) throws IOException {
NcbiGeneInfoFileParser parser = new NcbiGeneInfoFileParser(geneInfoFile, CharacterEncoding.UTF_8);
return buildConceptMapperDictionary(dictionaryFile, taxonomyIdsToInclude, parser, cleanDictFile);
}
public static File buildConceptMapperDictionary(File workDirectory, CleanDirectory cleanWorkDirectory,
Set<NcbiTaxonomyID> taxonomyIdsToInclude) throws IOException {
boolean doClean = cleanWorkDirectory.equals(CleanDirectory.YES);
NcbiGeneInfoFileParser parser = new NcbiGeneInfoFileParser(workDirectory, doClean);
return buildConceptMapperDictionary(workDirectory, taxonomyIdsToInclude, parser, doClean);
}
/**
* @param workDirectory
* @param taxonomyIdsToInclude
* @param parser
* @return
* @throws IOException
*/
private static File buildConceptMapperDictionary(File dictionaryFile, Set<NcbiTaxonomyID> taxonomyIdsToInclude,
NcbiGeneInfoFileParser parser, boolean cleanDictFile) throws IOException {
if (dictionaryFile.exists()) {
if (cleanDictFile) {
FileUtil.deleteFile(dictionaryFile);
} else {
return dictionaryFile;
}
}
ConceptMapperDictionaryBuilder dictBuilder = new ConceptMapperDictionaryBuilder(dictionaryFile,
MINIMUM_TERM_LENGTH);
int count = 0;
while (parser.hasNext()) {
if (count++ % 100000 == 0)
logger.info("Progress: " + (count - 1));
NcbiGeneInfoFileData dataRecord = parser.next();
NcbiTaxonomyID taxonID = dataRecord.getTaxonID();
boolean useRecord = true;
if (taxonomyIdsToInclude != null && !taxonomyIdsToInclude.isEmpty()) {
useRecord = taxonomyIdsToInclude.contains(taxonID);
}
if (useRecord) {
List<String> synonymStrs = new ArrayList<String>();
String nomSymbol = dataRecord.getSymbolFromNomenclatureAuthority();
if (nomSymbol != null)
synonymStrs.add(nomSymbol);
String nomName = dataRecord.getFullNameFromNomenclatureAuthority();
if (nomName != null)
synonymStrs.add(nomName);
String symbol = dataRecord.getSymbol();
if (symbol != null)
synonymStrs.add(symbol);
Set<String> synonyms = dataRecord.getSynonyms();
if (synonyms != null)
for (String syn : synonyms)
synonymStrs.add(syn);
Set<String> otherDesignations = dataRecord.getOtherDesignations();
if (otherDesignations != null)
for (String desig : otherDesignations)
synonymStrs.add(desig);
synonymStrs = filterSynonyms(synonymStrs);
dictBuilder.addEntry(dataRecord.getGeneID().getId().toString(), synonymStrs);
}
}
dictBuilder.close();
return dictionaryFile;
}
/**
* @param synonymStrs
* @return
*/
private static List<String> filterSynonyms(List<String> synonymStrs) {
List<String> filteredSyns = new ArrayList<String>();
for (String syn : synonymStrs) {
boolean ignore = false;
for (String ignoreStr : SYNONYMS_TO_IGNORE) {
if (syn.contains(ignoreStr)) {
ignore = true;
break;
}
}
if (!ignore)
filteredSyns.add(syn);
}
return filteredSyns;
}
}
|
package org.openhealthtools.mdht.uml.hl7.datatypes.impl;
import org.eclipse.emf.ecore.EClass;
import org.eclipse.emf.ecore.EDataType;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.emf.ecore.EPackage;
import org.eclipse.emf.ecore.impl.EFactoryImpl;
import org.eclipse.emf.ecore.plugin.EcorePlugin;
import org.openhealthtools.mdht.uml.hl7.datatypes.*;
import org.openhealthtools.mdht.uml.hl7.vocab.AddressPartType;
import org.openhealthtools.mdht.uml.hl7.vocab.EntityNamePartType;
import org.openhealthtools.mdht.uml.hl7.vocab.NullFlavor;
/**
* <!-- begin-user-doc -->
* An implementation of the model <b>Factory</b>.
* <!-- end-user-doc -->
* @generated
*/
public class DatatypesFactoryImpl extends EFactoryImpl implements DatatypesFactory {
/**
* Creates the default factory implementation.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public static DatatypesFactory init() {
try {
DatatypesFactory theDatatypesFactory = (DatatypesFactory)EPackage.Registry.INSTANCE.getEFactory("http:
if (theDatatypesFactory != null) {
return theDatatypesFactory;
}
}
catch (Exception exception) {
EcorePlugin.INSTANCE.log(exception);
}
return new DatatypesFactoryImpl();
}
/**
* Creates an instance of the factory.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public DatatypesFactoryImpl() {
super();
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public EObject create(EClass eClass) {
switch (eClass.getClassifierID()) {
case DatatypesPackage.ED: return createED();
case DatatypesPackage.TEL: return createTEL();
case DatatypesPackage.SXCM_TS: return createSXCM_TS();
case DatatypesPackage.TS: return createTS();
case DatatypesPackage.ST: return createST();
case DatatypesPackage.CD: return createCD();
case DatatypesPackage.CR: return createCR();
case DatatypesPackage.CV: return createCV();
case DatatypesPackage.CE: return createCE();
case DatatypesPackage.II: return createII();
case DatatypesPackage.BL: return createBL();
case DatatypesPackage.BN: return createBN();
case DatatypesPackage.AD: return createAD();
case DatatypesPackage.ADXP: return createADXP();
case DatatypesPackage.EN: return createEN();
case DatatypesPackage.IVL_TS: return createIVL_TS();
case DatatypesPackage.IVXB_TS: return createIVXB_TS();
case DatatypesPackage.PQ: return createPQ();
case DatatypesPackage.PQR: return createPQR();
case DatatypesPackage.ENXP: return createENXP();
case DatatypesPackage.ON: return createON();
case DatatypesPackage.PN: return createPN();
case DatatypesPackage.TN: return createTN();
case DatatypesPackage.INT: return createINT();
case DatatypesPackage.REAL: return createREAL();
case DatatypesPackage.CS: return createCS();
case DatatypesPackage.CO: return createCO();
case DatatypesPackage.SC: return createSC();
case DatatypesPackage.RTO_QTY_QTY: return createRTO_QTY_QTY();
case DatatypesPackage.MO: return createMO();
case DatatypesPackage.RTO: return createRTO();
case DatatypesPackage.SXCM_INT: return createSXCM_INT();
case DatatypesPackage.IVXB_INT: return createIVXB_INT();
case DatatypesPackage.IVL_INT: return createIVL_INT();
case DatatypesPackage.IVXB_PQ: return createIVXB_PQ();
case DatatypesPackage.SXCM_PQ: return createSXCM_PQ();
case DatatypesPackage.IVL_PQ: return createIVL_PQ();
case DatatypesPackage.RTO_PQ_PQ: return createRTO_PQ_PQ();
case DatatypesPackage.PIVL_TS: return createPIVL_TS();
default:
throw new IllegalArgumentException("The class '" + eClass.getName() + "' is not a valid classifier");
}
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public Object createFromString(EDataType eDataType, String initialValue) {
switch (eDataType.getClassifierID()) {
case DatatypesPackage.BINARY_DATA_ENCODING:
return createBinaryDataEncodingFromString(eDataType, initialValue);
default:
throw new IllegalArgumentException("The datatype '" + eDataType.getName() + "' is not a valid classifier");
}
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public String convertToString(EDataType eDataType, Object instanceValue) {
switch (eDataType.getClassifierID()) {
case DatatypesPackage.BINARY_DATA_ENCODING:
return convertBinaryDataEncodingToString(eDataType, instanceValue);
default:
throw new IllegalArgumentException("The datatype '" + eDataType.getName() + "' is not a valid classifier");
}
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public ED createED() {
EDImpl ed = new EDImpl();
return ed;
}
public ED createED(String text) {
ED ed = createED();
ed.addText(text);
return ed;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public TEL createTEL() {
TELImpl tel = new TELImpl();
return tel;
}
public TEL createTEL(String value) {
TEL tel = new TELImpl();
tel.setValue(value);
return tel;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public SXCM_TS createSXCM_TS() {
SXCM_TSImpl sxcM_TS = new SXCM_TSImpl();
return sxcM_TS;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public TS createTS() {
TSImpl ts = new TSImpl();
return ts;
}
public TS createTS(String value) {
TS ts = createTS();
ts.setValue(value);
return ts;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public ST createST() {
STImpl st = new STImpl();
return st;
}
public ST createST(String text) {
ST st = createST();
st.addText(text);
return st;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public CD createCD() {
CDImpl cd = new CDImpl();
return cd;
}
public CD createCD(String code, String codeSystem, String codeSystemName, String displayName) {
CD cd = createCD();
cd.setCode(code);
cd.setCodeSystem(codeSystem);
cd.setCodeSystemName(codeSystemName);
cd.setDisplayName(displayName);
return cd;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public CR createCR() {
CRImpl cr = new CRImpl();
return cr;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public CV createCV() {
CVImpl cv = new CVImpl();
return cv;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public CE createCE() {
CEImpl ce = new CEImpl();
return ce;
}
public CE createCE(String code, String codeSystem) {
CE ce = createCE();
ce.setCode(code);
ce.setCodeSystem(codeSystem);
return ce;
}
public CE createCE(String code, String codeSystem, String codeSystemName, String displayName) {
CE ce = createCE(code, codeSystem);
ce.setCodeSystemName(codeSystemName);
ce.setDisplayName(displayName);
return ce;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public II createII() {
IIImpl ii = new IIImpl();
return ii;
}
public II createII(String root) {
II ii = createII();
ii.setRoot(root);
return ii;
}
public II createII(String root, String extension) {
II ii = createII(root);
ii.setExtension(extension);
return ii;
}
public II createII(NullFlavor nullFlavor) {
II ii = createII();
ii.setNullFlavor(nullFlavor);
return ii;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public BL createBL() {
BLImpl bl = new BLImpl();
return bl;
}
public BL createBL(Boolean value) {
BL bl = createBL();
bl.setValue(value);
return bl;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public BN createBN() {
BNImpl bn = new BNImpl();
return bn;
}
public BN createBN(Boolean value) {
BN bn = createBN();
bn.setValue(value);
return bn;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public AD createAD() {
ADImpl ad = new ADImpl();
return ad;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public ADXP createADXP() {
ADXPImpl adxp = new ADXPImpl();
return adxp;
}
public ADXP createADXP(AddressPartType partType, String text) {
ADXP adxp = createADXP();
adxp.setPartType(partType);
adxp.addText(text);
return adxp;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public EN createEN() {
ENImpl en = new ENImpl();
return en;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public IVL_TS createIVL_TS() {
IVL_TSImpl ivl_ts = new IVL_TSImpl();
return ivl_ts;
}
public IVL_TS createIVL_TS(String high, String low) {
IVL_TS ivl_ts = createIVL_TS();
if (low != null) {
IVXB_TS lower = createIVXB_TS();
lower.setValue(low);
ivl_ts.setLow(lower);
}
if (high != null) {
IVXB_TS higher = createIVXB_TS();
higher.setValue(high);
ivl_ts.setHigh(higher);
}
return ivl_ts;
}
public IVL_TS createIVL_TS(String value) {
IVL_TS ivl_ts = createIVL_TS();
ivl_ts.setValue(value);
return ivl_ts;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public IVXB_TS createIVXB_TS() {
IVXB_TSImpl ivxB_TS = new IVXB_TSImpl();
return ivxB_TS;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public PQ createPQ() {
PQImpl pq = new PQImpl();
return pq;
}
public PQ createPQ(double value, String unit) {
PQ pq = createPQ();
pq.setValue(value);
pq.setUnit(unit);
return pq;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public PQR createPQR() {
PQRImpl pqr = new PQRImpl();
return pqr;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public ENXP createENXP() {
ENXPImpl enxp = new ENXPImpl();
return enxp;
}
public ENXP createENXP(EntityNamePartType partType, String text) {
ENXP enxp = createENXP();
enxp.setPartType(partType);
enxp.addText(text);
return enxp;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public ON createON() {
ONImpl on = new ONImpl();
return on;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public PN createPN() {
PNImpl pn = new PNImpl();
return pn;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public TN createTN() {
TNImpl tn = new TNImpl();
return tn;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public INT createINT() {
INTImpl int_ = new INTImpl();
return int_;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public REAL createREAL() {
REALImpl real = new REALImpl();
return real;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public CS createCS() {
CSImpl cs = new CSImpl();
return cs;
}
public CS createCS(String code) {
CS cs = createCS();
cs.setCode(code);
return cs;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public CO createCO() {
COImpl co = new COImpl();
return co;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public SC createSC() {
SCImpl sc = new SCImpl();
return sc;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public RTO_QTY_QTY createRTO_QTY_QTY() {
RTO_QTY_QTYImpl rtO_QTY_QTY = new RTO_QTY_QTYImpl();
return rtO_QTY_QTY;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public MO createMO() {
MOImpl mo = new MOImpl();
return mo;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public RTO createRTO() {
RTOImpl rto = new RTOImpl();
return rto;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public SXCM_INT createSXCM_INT() {
SXCM_INTImpl sxcM_INT = new SXCM_INTImpl();
return sxcM_INT;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public IVXB_INT createIVXB_INT() {
IVXB_INTImpl ivxB_INT = new IVXB_INTImpl();
return ivxB_INT;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public IVL_INT createIVL_INT() {
IVL_INTImpl ivL_INT = new IVL_INTImpl();
return ivL_INT;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public IVXB_PQ createIVXB_PQ() {
IVXB_PQImpl ivxB_PQ = new IVXB_PQImpl();
return ivxB_PQ;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public SXCM_PQ createSXCM_PQ() {
SXCM_PQImpl sxcM_PQ = new SXCM_PQImpl();
return sxcM_PQ;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public IVL_PQ createIVL_PQ() {
IVL_PQImpl ivL_PQ = new IVL_PQImpl();
return ivL_PQ;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public RTO_PQ_PQ createRTO_PQ_PQ() {
RTO_PQ_PQImpl rtO_PQ_PQ = new RTO_PQ_PQImpl();
return rtO_PQ_PQ;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public PIVL_TS createPIVL_TS() {
PIVL_TSImpl pivL_TS = new PIVL_TSImpl();
return pivL_TS;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public BinaryDataEncoding createBinaryDataEncodingFromString(EDataType eDataType, String initialValue) {
BinaryDataEncoding result = BinaryDataEncoding.get(initialValue);
if (result == null) throw new IllegalArgumentException("The value '" + initialValue + "' is not a valid enumerator of '" + eDataType.getName() + "'");
return result;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public String convertBinaryDataEncodingToString(EDataType eDataType, Object instanceValue) {
return instanceValue == null ? null : instanceValue.toString();
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public DatatypesPackage getDatatypesPackage() {
return (DatatypesPackage)getEPackage();
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @deprecated
* @generated
*/
@Deprecated
public static DatatypesPackage getPackage() {
return DatatypesPackage.eINSTANCE;
}
} //DatatypesFactoryImpl
|
package org.csstudio.trends.databrowser3.waveformview;
import java.util.ArrayList;
import java.util.List;
import org.csstudio.archive.vtype.TimestampHelper;
import org.csstudio.archive.vtype.VTypeHelper;
import org.csstudio.javafx.rtplot.PointType;
import org.csstudio.javafx.rtplot.RTValuePlot;
import org.csstudio.javafx.rtplot.Trace;
import org.csstudio.javafx.rtplot.TraceType;
import org.csstudio.trends.databrowser3.Activator;
import org.csstudio.trends.databrowser3.Messages;
import org.csstudio.trends.databrowser3.editor.DataBrowserAwareView;
import org.csstudio.trends.databrowser3.model.Model;
import org.csstudio.trends.databrowser3.model.ModelItem;
import org.csstudio.trends.databrowser3.model.ModelListener;
import org.csstudio.trends.databrowser3.model.ModelListenerAdapter;
import org.csstudio.trends.databrowser3.model.PlotSamples;
import org.diirt.vtype.VNumberArray;
import org.diirt.vtype.VType;
import org.eclipse.osgi.util.NLS;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.DisposeEvent;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Combo;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Slider;
import org.eclipse.swt.widgets.Text;
import javafx.embed.swt.FXCanvas;
import javafx.scene.Scene;
/** View for inspecting Waveform (Array) Samples of the current Model
* @author Kay Kasemir
* @author Takashi Nakamoto changed WaveformView to handle multiple items with
* the same name.
* @author Xihui Chen (Added some work around to make it work for rap).
*/
@SuppressWarnings("nls")
public class WaveformView extends DataBrowserAwareView
{
/** View ID registered in plugin.xml */
final public static String ID =
"org.csstudio.trends.databrowser.waveformview.WaveformView"; //$NON-NLS-1$
/** PV Name selector */
private Combo pv_name;
/** Plot */
private RTValuePlot plot;
/** Selector for model_item's current sample */
private Slider sample_index;
/** Timestamp of current sample. */
private Text timestamp;
/** Status/severity of current sample. */
private Text status;
/** Model of the currently active Data Browser plot or <code>null</code> */
private Model model;
final private ModelListener model_listener = new ModelListenerAdapter()
{
@Override
public void itemAdded(final ModelItem item)
{
update(false);
}
@Override
public void itemRemoved(final ModelItem item)
{
if (item == model_item)
model_item = null;
// Will update the combo to reflect missing item,
// then detect model_item change and selectPV(null)
update(false);
}
@Override
public void changedItemLook(final ModelItem item)
{
update(false);
}
};
/** Selected model item in model, or <code>null</code> */
private ModelItem model_item = null;
/** Waveform for the currently selected sample */
private WaveformValueDataProvider waveform = null;
/** {@inheritDoc} */
@Override
protected void doCreatePartControl(final Composite parent)
{
// Arrange disposal
parent.addDisposeListener((DisposeEvent e) ->
{ // Ignore current model after this view is disposed.
if (model != null)
model.removeListener(model_listener);
});
final GridLayout layout = new GridLayout(4, false);
parent.setLayout(layout);
// PV: .pvs..... [Refresh]
// <<<<<< Slider >>>>>>
// PV: .pvs..... [Refresh]
Label l = new Label(parent, 0);
l.setText(Messages.SampleView_Item);
l.setLayoutData(new GridData());
pv_name = new Combo(parent, SWT.DROP_DOWN | SWT.READ_ONLY);
pv_name.setLayoutData(new GridData(SWT.FILL, 0, true, false, layout.numColumns-2, 1));
pv_name.addSelectionListener(new SelectionListener()
{
@Override
public void widgetSelected(final SelectionEvent e)
{
widgetDefaultSelected(e);
}
@Override
public void widgetDefaultSelected(final SelectionEvent e)
{ // First item is "--select PV name--"
if (pv_name.getSelectionIndex() == 0)
selectPV(null);
else
selectPV(model.getItem(pv_name.getText()));
}
});
final Button refresh = new Button(parent, SWT.PUSH);
refresh.setText(Messages.SampleView_Refresh);
refresh.setToolTipText(Messages.SampleView_RefreshTT);
refresh.setLayoutData(new GridData());
refresh.addSelectionListener(new SelectionAdapter()
{
@Override
public void widgetSelected(final SelectionEvent e)
{ // First item is "--select PV name--"
if (pv_name.getSelectionIndex() == 0)
selectPV(null);
else
selectPV(model.getItem(pv_name.getText()));
}
});
final FXCanvas plot_canvas = new FXCanvas(parent, SWT.NONE);
plot = new RTValuePlot(true);
plot.getXAxis().setName(Messages.WaveformIndex);
plot.getYAxes().get(0).setName(Messages.WaveformAmplitude);
plot.getYAxes().get(0).setAutoscale(true);
plot_canvas.setScene(new Scene(plot));
plot_canvas.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, layout.numColumns, 1));
// <<<<<< Slider >>>>>>
sample_index = new Slider(parent, SWT.HORIZONTAL);
sample_index.setToolTipText(Messages.WaveformTimeSelector);
sample_index.setLayoutData(new GridData(SWT.FILL, 0, true, false, layout.numColumns, 1));
sample_index.addSelectionListener(new SelectionAdapter()
{
@Override
public void widgetSelected(SelectionEvent e)
{
showSelectedSample();
}
});
l = new Label(parent, 0);
l.setText(Messages.WaveformTimestamp);
l.setLayoutData(new GridData());
timestamp = new Text(parent, SWT.BORDER | SWT.READ_ONLY);
timestamp.setLayoutData(new GridData(SWT.FILL, 0, true, false));
l = new Label(parent, 0);
l.setText(Messages.WaveformStatus);
l.setLayoutData(new GridData());
status = new Text(parent, SWT.BORDER | SWT.READ_ONLY);
status.setLayoutData(new GridData(SWT.FILL, 0, true, false));
}
/** {@inheritDoc} */
@Override
public void setFocus()
{
pv_name.setFocus();
}
/** {@inheritDoc} */
@Override
protected void updateModel(final Model old_model, final Model model)
{
this.model = model;
if (old_model != model)
{
if (old_model != null)
old_model.removeListener(model_listener);
if (model != null)
model.addListener(model_listener);
}
update(old_model != model);
}
/** Update combo box of this view.
* Since it interacts with the UI run on the UI thread.
* @param model_changed Is this a different model?
*/
private void update(final boolean model_changed)
{
pv_name.getDisplay().asyncExec( () ->
{
if (pv_name.isDisposed())
return;
if (model == null)
{ // Clear/disable GUI
pv_name.setItems(new String[] { Messages.SampleView_NoPlot});
pv_name.select(0);
pv_name.setEnabled(false);
selectPV(null);
return;
}
// Show PV names
final List<String> names_list = new ArrayList<>();
names_list.add(Messages.SampleView_SelectItem);
for (ModelItem item : model.getItems())
names_list.add(item.getName());
final String[] names = names_list.toArray(new String[names_list.size()]);
// Is the previously selected item still valid?
final int selected = pv_name.getSelectionIndex();
if (!model_changed && selected > 0 && model_item != null && pv_name.getText().equals(model_item.getName()))
{
// Show same PV name again in combo box
pv_name.setItems(names);
pv_name.select(selected);
pv_name.setEnabled(true);
return;
}
// Previously selected item no longer valid.
// Show new items, clear rest
pv_name.setItems(names);
pv_name.select(0);
pv_name.setEnabled(true);
selectPV(null);
});
}
/** Select given PV item (or <code>null</code>). */
private void selectPV(final ModelItem new_item)
{
model_item = new_item;
// Delete all existing traces
for (Trace<Double> trace : plot.getTraces())
plot.removeTrace(trace);
// No or unknown PV name?
if (model_item == null)
{
pv_name.setText(""); //$NON-NLS-1$
sample_index.setEnabled(false);
return;
}
// Prepare to show waveforms of model item in plot
waveform = new WaveformValueDataProvider();
// Create trace for waveform
plot.addTrace(model_item.getResolvedDisplayName(), model_item.getUnits(), waveform, model_item.getPaintColor(), TraceType.NONE, 1, PointType.CIRCLES, 5, 0);
// Enable waveform selection and update slider's range
sample_index.setEnabled(true);
showSelectedSample();
// Autoscale Y axis by default.
plot.getYAxes().get(0).setAutoscale(true);
}
/** Show the current sample of the current model item. */
private void showSelectedSample()
{
// Get selected sample (= one waveform)
final PlotSamples samples = model_item.getSamples();
final VType value;
samples.getLock().lock();
try
{
sample_index.setMaximum(samples.size());
final int idx = sample_index.getSelection();
value = samples.get(idx).getVType();
}
finally
{
samples.getLock().unlock();
}
// Setting the value can be delayed while the plot is being updated
Activator.getThreadPool().execute(() -> waveform.setValue(value));
if (value == null)
clearInfo();
else
{
int size = value instanceof VNumberArray ? ((VNumberArray)value).getData().size() : 1;
plot.getXAxis().setValueRange(0.0, (double)size);
timestamp.setText(TimestampHelper.format(VTypeHelper.getTimestamp(value)));
status.setText(NLS.bind(Messages.SeverityStatusFmt, VTypeHelper.getSeverity(value).toString(), VTypeHelper.getMessage(value)));
}
plot.requestUpdate();
}
/** Clear all the info fields. */
private void clearInfo()
{
timestamp.setText("");
status.setText("");
}
}
|
package org.eclipse.smarthome.binding.sonos.internal;
import java.io.IOException;
import java.io.StringReader;
import java.net.URL;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.xml.sax.Attributes;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.DefaultHandler;
import org.xml.sax.helpers.XMLReaderFactory;
/**
* The {@link SonosXMLParser} is a class of helper functions
* to parse XML data returned by the Zone Players
*
* @author Karel Goderis - Initial contribution
*/
public class SonosXMLParser {
static final Logger logger = LoggerFactory.getLogger(SonosXMLParser.class);
private static MessageFormat METADATA_FORMAT = new MessageFormat(
"<DIDL-Lite xmlns:dc=\"http://purl.org/dc/elements/1.1/\" "
+ "xmlns:upnp=\"urn:schemas-upnp-org:metadata-1-0/upnp/\" "
+ "xmlns:r=\"urn:schemas-rinconnetworks-com:metadata-1-0/\" "
+ "xmlns=\"urn:schemas-upnp-org:metadata-1-0/DIDL-Lite/\">"
+ "<item id=\"{0}\" parentID=\"{1}\" restricted=\"true\">" + "<dc:title>{2}</dc:title>"
+ "<upnp:class>{3}</upnp:class>"
+ "<desc id=\"cdudn\" nameSpace=\"urn:schemas-rinconnetworks-com:metadata-1-0/\">" + "{4}</desc>"
+ "</item></DIDL-Lite>");
private enum Element {
TITLE,
CLASS,
ALBUM,
ALBUM_ART_URI,
CREATOR,
RES,
TRACK_NUMBER,
RESMD,
DESC
}
private enum CurrentElement {
item,
res,
streamContent,
albumArtURI,
title,
upnpClass,
creator,
album,
albumArtist,
desc;
}
/**
* @param xml
* @return a list of alarms from the given xml string.
* @throws IOException
* @throws SAXException
*/
public static List<SonosAlarm> getAlarmsFromStringResult(String xml) {
AlarmHandler handler = new AlarmHandler();
try {
XMLReader reader = XMLReaderFactory.createXMLReader();
reader.setContentHandler(handler);
reader.parse(new InputSource(new StringReader(xml)));
} catch (IOException e) {
logger.error("Could not parse Alarms from string '{}'", xml);
} catch (SAXException s) {
logger.error("Could not parse Alarms from string '{}'", xml);
}
return handler.getAlarms();
}
/**
* @param xml
* @return a list of Entries from the given xml string.
* @throws IOException
* @throws SAXException
*/
public static List<SonosEntry> getEntriesFromString(String xml) {
EntryHandler handler = new EntryHandler();
try {
XMLReader reader = XMLReaderFactory.createXMLReader();
reader.setContentHandler(handler);
reader.parse(new InputSource(new StringReader(xml)));
} catch (IOException e) {
logger.error("Could not parse Entries from string '{}'", xml);
} catch (SAXException s) {
logger.error("Could not parse Entries from string '{}'", xml);
}
return handler.getArtists();
}
/**
* Returns the meta data which is needed to play Pandora
* (and others?) favorites
*
* @param xml
* @return The value of the desc xml tag
* @throws SAXException
*/
public static SonosResourceMetaData getResourceMetaData(String xml) throws SAXException {
XMLReader reader = XMLReaderFactory.createXMLReader();
ResourceMetaDataHandler handler = new ResourceMetaDataHandler();
reader.setContentHandler(handler);
try {
reader.parse(new InputSource(new StringReader(xml)));
} catch (IOException e) {
logger.error("Could not parse Resource MetaData from String '{}'", xml);
} catch (SAXException s) {
logger.error("Could not parse Resource MetaData from string '{}'", xml);
}
return handler.getMetaData();
}
/**
* @param controller
* @param xml
* @return zone group from the given xml
* @throws IOException
* @throws SAXException
*/
public static List<SonosZoneGroup> getZoneGroupFromXML(String xml) {
ZoneGroupHandler handler = new ZoneGroupHandler();
try {
XMLReader reader = XMLReaderFactory.createXMLReader();
reader.setContentHandler(handler);
reader.parse(new InputSource(new StringReader(xml)));
} catch (IOException e) {
// This should never happen - we're not performing I/O!
logger.error("Could not parse ZoneGroup from string '{}'", xml);
} catch (SAXException s) {
logger.error("Could not parse ZoneGroup from string '{}'", xml);
}
return handler.getGroups();
}
public static List<String> getRadioTimeFromXML(String xml) {
OpmlHandler handler = new OpmlHandler();
try {
XMLReader reader = XMLReaderFactory.createXMLReader();
reader.setContentHandler(handler);
reader.parse(new InputSource(new StringReader(xml)));
} catch (IOException e) {
// This should never happen - we're not performing I/O!
logger.error("Could not parse RadioTime from string '{}'", xml);
} catch (SAXException s) {
logger.error("Could not parse RadioTime from string '{}'", xml);
}
return handler.getTextFields();
}
public static Map<String, String> getRenderingControlFromXML(String xml) {
RenderingControlEventHandler handler = new RenderingControlEventHandler();
try {
XMLReader reader = XMLReaderFactory.createXMLReader();
reader.setContentHandler(handler);
reader.parse(new InputSource(new StringReader(xml)));
} catch (IOException e) {
// This should never happen - we're not performing I/O!
logger.error("Could not parse Rendering Control from string '{}'", xml);
} catch (SAXException s) {
logger.error("Could not parse Rendering Control from string '{}'", xml);
}
return handler.getChanges();
}
public static Map<String, String> getAVTransportFromXML(String xml) {
AVTransportEventHandler handler = new AVTransportEventHandler();
try {
XMLReader reader = XMLReaderFactory.createXMLReader();
reader.setContentHandler(handler);
reader.parse(new InputSource(new StringReader(xml)));
} catch (IOException e) {
// This should never happen - we're not performing I/O!
logger.error("Could not parse AV Transport from string '{}'", xml);
} catch (SAXException s) {
logger.error("Could not parse AV Transport from string '{}'", xml);
}
return handler.getChanges();
}
public static SonosMetaData getMetaDataFromXML(String xml) {
MetaDataHandler handler = new MetaDataHandler();
try {
XMLReader reader = XMLReaderFactory.createXMLReader();
reader.setContentHandler(handler);
reader.parse(new InputSource(new StringReader(xml)));
} catch (IOException e) {
// This should never happen - we're not performing I/O!
logger.error("Could not parse MetaData from string '{}'", xml);
} catch (SAXException s) {
logger.error("Could not parse MetaData from string '{}'", xml);
}
return handler.getMetaData();
}
static private class EntryHandler extends DefaultHandler {
// Maintain a set of elements about which it is unuseful to complain about.
// This list will be initialized on the first failure case
private static List<String> ignore = null;
private String id;
private String parentId;
private StringBuilder upnpClass = new StringBuilder();
private StringBuilder res = new StringBuilder();
private StringBuilder title = new StringBuilder();
private StringBuilder album = new StringBuilder();
private StringBuilder albumArtUri = new StringBuilder();
private StringBuilder creator = new StringBuilder();
private StringBuilder trackNumber = new StringBuilder();
private StringBuilder desc = new StringBuilder();
private Element element = null;
private List<SonosEntry> artists = new ArrayList<SonosEntry>();
EntryHandler() {
// shouldn't be used outside of this package.
}
@Override
public void startElement(String uri, String localName, String qName, Attributes attributes)
throws SAXException {
if (qName.equals("container") || qName.equals("item")) {
id = attributes.getValue("id");
parentId = attributes.getValue("parentID");
} else if (qName.equals("res")) {
element = Element.RES;
} else if (qName.equals("dc:title")) {
element = Element.TITLE;
} else if (qName.equals("upnp:class")) {
element = Element.CLASS;
} else if (qName.equals("dc:creator")) {
element = Element.CREATOR;
} else if (qName.equals("upnp:album")) {
element = Element.ALBUM;
} else if (qName.equals("upnp:albumArtURI")) {
element = Element.ALBUM_ART_URI;
} else if (qName.equals("upnp:originalTrackNumber")) {
element = Element.TRACK_NUMBER;
} else if (qName.equals("r:resMD")) {
element = Element.RESMD;
} else {
if (ignore == null) {
ignore = new ArrayList<String>();
ignore.add("DIDL-Lite");
ignore.add("type");
ignore.add("ordinal");
ignore.add("description");
}
if (!ignore.contains(localName)) {
logger.debug("Did not recognise element named {}", localName);
}
element = null;
}
}
@Override
public void characters(char[] ch, int start, int length) throws SAXException {
if (element == null) {
return;
}
switch (element) {
case TITLE:
title.append(ch, start, length);
break;
case CLASS:
upnpClass.append(ch, start, length);
break;
case RES:
res.append(ch, start, length);
break;
case ALBUM:
album.append(ch, start, length);
break;
case ALBUM_ART_URI:
albumArtUri.append(ch, start, length);
break;
case CREATOR:
creator.append(ch, start, length);
break;
case TRACK_NUMBER:
trackNumber.append(ch, start, length);
break;
case RESMD:
desc.append(ch, start, length);
break;
case DESC:
break;
}
}
@Override
public void endElement(String uri, String localName, String qName) throws SAXException {
if (qName.equals("container") || qName.equals("item")) {
element = null;
int trackNumberVal = 0;
try {
trackNumberVal = Integer.parseInt(trackNumber.toString());
} catch (Exception e) {
}
SonosResourceMetaData md = null;
// The resource description is needed for playing favorites on pandora
if (!desc.toString().isEmpty()) {
try {
md = getResourceMetaData(desc.toString());
} catch (SAXException ignore) {
logger.debug("Failed to parse embeded", ignore);
}
}
artists.add(new SonosEntry(id, title.toString(), parentId, album.toString(), albumArtUri.toString(),
creator.toString(), upnpClass.toString(), res.toString(), trackNumberVal, md));
title = new StringBuilder();
upnpClass = new StringBuilder();
res = new StringBuilder();
album = new StringBuilder();
albumArtUri = new StringBuilder();
creator = new StringBuilder();
trackNumber = new StringBuilder();
desc = new StringBuilder();
}
}
public List<SonosEntry> getArtists() {
return artists;
}
}
static private class ResourceMetaDataHandler extends DefaultHandler {
private String id;
private String parentId;
private StringBuilder title = new StringBuilder();
private StringBuilder upnpClass = new StringBuilder();
private StringBuilder desc = new StringBuilder();
private Element element = null;
private SonosResourceMetaData metaData = null;
ResourceMetaDataHandler() {
// shouldn't be used outside of this package.
}
@Override
public void startElement(String uri, String localName, String qName, Attributes attributes)
throws SAXException {
if (qName.equals("container") || qName.equals("item")) {
id = attributes.getValue("id");
parentId = attributes.getValue("parentID");
} else if (qName.equals("desc")) {
element = Element.DESC;
} else if (qName.equals("upnp:class")) {
element = Element.CLASS;
} else if (qName.equals("dc:title")) {
element = Element.TITLE;
} else {
element = null;
}
}
@Override
public void characters(char[] ch, int start, int length) throws SAXException {
if (element == null) {
return;
}
switch (element) {
case TITLE:
title.append(ch, start, length);
break;
case CLASS:
upnpClass.append(ch, start, length);
break;
case DESC:
desc.append(ch, start, length);
;
break;
default:
break;
}
}
@Override
public void endElement(String uri, String localName, String qName) throws SAXException {
if (qName.equals("DIDL-Lite")) {
metaData = new SonosResourceMetaData(id, parentId, title.toString(), upnpClass.toString(),
desc.toString());
element = null;
desc = new StringBuilder();
upnpClass = new StringBuilder();
title = new StringBuilder();
}
}
public SonosResourceMetaData getMetaData() {
return metaData;
}
}
static private class AlarmHandler extends DefaultHandler {
private String id;
private String startTime;
private String duration;
private String recurrence;
private String enabled;
private String roomUUID;
private String programURI;
private String programMetaData;
private String playMode;
private String volume;
private String includeLinkedZones;
private List<SonosAlarm> alarms = new ArrayList<SonosAlarm>();
AlarmHandler() {
// shouldn't be used outside of this package.
}
@Override
public void startElement(String uri, String localName, String qName, Attributes attributes)
throws SAXException {
if (qName.equals("Alarm")) {
id = attributes.getValue("ID");
duration = attributes.getValue("Duration");
recurrence = attributes.getValue("Recurrence");
startTime = attributes.getValue("StartTime");
enabled = attributes.getValue("Enabled");
roomUUID = attributes.getValue("RoomUUID");
programURI = attributes.getValue("ProgramURI");
programMetaData = attributes.getValue("ProgramMetaData");
playMode = attributes.getValue("PlayMode");
volume = attributes.getValue("Volume");
includeLinkedZones = attributes.getValue("IncludeLinkedZones");
}
}
@Override
public void endElement(String uri, String localName, String qName) throws SAXException {
if (qName.equals("Alarm")) {
int finalID = 0;
int finalVolume = 0;
boolean finalEnabled = false;
boolean finalIncludeLinkedZones = false;
try {
finalID = Integer.parseInt(id);
finalVolume = Integer.parseInt(volume);
if (enabled.equals("0")) {
finalEnabled = false;
} else {
finalEnabled = true;
}
if (includeLinkedZones.equals("0")) {
finalIncludeLinkedZones = false;
} else {
finalIncludeLinkedZones = true;
}
} catch (Exception e) {
logger.debug("Error parsing Integer");
}
alarms.add(new SonosAlarm(finalID, startTime, duration, recurrence, finalEnabled, roomUUID, programURI,
programMetaData, playMode, finalVolume, finalIncludeLinkedZones));
}
}
public List<SonosAlarm> getAlarms() {
return alarms;
}
}
static private class ZoneGroupHandler extends DefaultHandler {
private final List<SonosZoneGroup> groups = new ArrayList<SonosZoneGroup>();
private final List<String> currentGroupPlayers = new ArrayList<String>();
private final List<String> currentGroupPlayerZones = new ArrayList<String>();
private String coordinator;
private String groupId;
@Override
public void startElement(String uri, String localName, String qName, Attributes attributes)
throws SAXException {
if (qName.equals("ZoneGroup")) {
groupId = attributes.getValue("ID");
coordinator = attributes.getValue("Coordinator");
} else if (qName.equals("ZoneGroupMember")) {
currentGroupPlayers.add(attributes.getValue("UUID"));
String zoneName = attributes.getValue("ZoneName");
if (zoneName != null) {
currentGroupPlayerZones.add(zoneName);
}
String htInfoSet = attributes.getValue("HTSatChanMapSet");
if (htInfoSet != null) {
currentGroupPlayers.addAll(getAllHomeTheaterMembers(htInfoSet));
}
}
}
@Override
public void endElement(String uri, String localName, String qName) throws SAXException {
if (qName.equals("ZoneGroup")) {
groups.add(new SonosZoneGroup(groupId, coordinator, currentGroupPlayers, currentGroupPlayerZones));
currentGroupPlayers.clear();
currentGroupPlayerZones.clear();
}
}
public List<SonosZoneGroup> getGroups() {
return groups;
}
private Set<String> getAllHomeTheaterMembers(String homeTheaterDescription) {
Set<String> homeTheaterMembers = new HashSet<String>();
Matcher matcher = Pattern.compile("(RINCON_\\w+)").matcher(homeTheaterDescription);
while (matcher.find()) {
String member = matcher.group();
homeTheaterMembers.add(member);
}
return homeTheaterMembers;
}
}
static private class OpmlHandler extends DefaultHandler {
// <opml version="1">
// <head>
// <status>200</status>
// </head>
// <body>
// <outline type="text" text="Q-Music 103.3" guide_id="s2398" key="station"
// <outline type="text" text="Bjorn Verhoeven" guide_id="p257265" seconds_remaining="2230" duration="7200"
// key="show"/>
// <outline type="text" text="Top 40-Pop"/>
// <outline type="text" text="37m remaining"/>
// <outline type="object" text="NowPlaying">
// <nowplaying>
// <twitter_id />
// </nowplaying>
// </outline>
// </body>
// </opml>
private final List<String> textFields = new ArrayList<String>();
private String textField;
private String type;
// private String logo;
@Override
public void startElement(String uri, String localName, String qName, Attributes attributes)
throws SAXException {
if (qName.equals("outline")) {
type = attributes.getValue("type");
if (type.equals("text")) {
textField = attributes.getValue("text");
} else {
textField = null;
}
} else if (qName.equals("logo")) {
// logo = attributes.getValue("UUID");
}
}
@Override
public void endElement(String uri, String localName, String qName) throws SAXException {
if (qName.equals("outline")) {
if (textField != null) {
textFields.add(textField);
}
}
}
public List<String> getTextFields() {
return textFields;
}
}
static private class AVTransportEventHandler extends DefaultHandler {
private final Map<String, String> changes = new HashMap<String, String>();
@Override
public void startElement(String uri, String localName, String qName, Attributes atts) throws SAXException {
/*
* The events are all of the form <qName val="value"/> so we can get all
* the info we need from here.
*/
try {
if (atts.getValue("val") != null) {
changes.put(localName, atts.getValue("val"));
}
} catch (IllegalArgumentException e) {
// this means that localName isn't defined in EventType, which is expected for some elements
logger.info("{} is not defined in EventType. ", localName);
}
}
public Map<String, String> getChanges() {
return changes;
}
}
static private class MetaDataHandler extends DefaultHandler {
private CurrentElement currentElement = null;
private String id = "-1";
private String parentId = "-1";
private StringBuilder resource = new StringBuilder();
private StringBuilder streamContent = new StringBuilder();
private StringBuilder albumArtUri = new StringBuilder();
private StringBuilder title = new StringBuilder();
private StringBuilder upnpClass = new StringBuilder();
private StringBuilder creator = new StringBuilder();
private StringBuilder album = new StringBuilder();
private StringBuilder albumArtist = new StringBuilder();
@Override
public void startElement(String uri, String localName, String qName, Attributes atts) throws SAXException {
if ("item".equals(localName)) {
currentElement = CurrentElement.item;
id = atts.getValue("id");
parentId = atts.getValue("parentID");
} else if ("res".equals(localName)) {
currentElement = CurrentElement.res;
} else if ("streamContent".equals(localName)) {
currentElement = CurrentElement.streamContent;
} else if ("albumArtURI".equals(localName)) {
currentElement = CurrentElement.albumArtURI;
} else if ("title".equals(localName)) {
currentElement = CurrentElement.title;
} else if ("class".equals(localName)) {
currentElement = CurrentElement.upnpClass;
} else if ("creator".equals(localName)) {
currentElement = CurrentElement.creator;
} else if ("album".equals(localName)) {
currentElement = CurrentElement.album;
} else if ("albumArtist".equals(localName)) {
currentElement = CurrentElement.albumArtist;
} else {
// unknown element
currentElement = null;
}
}
@Override
public void characters(char[] ch, int start, int length) throws SAXException {
if (currentElement != null) {
switch (currentElement) {
case item:
break;
case res:
resource.append(ch, start, length);
break;
case streamContent:
streamContent.append(ch, start, length);
break;
case albumArtURI:
albumArtUri.append(ch, start, length);
break;
case title:
title.append(ch, start, length);
break;
case upnpClass:
upnpClass.append(ch, start, length);
break;
case creator:
creator.append(ch, start, length);
break;
case album:
album.append(ch, start, length);
break;
case albumArtist:
albumArtist.append(ch, start, length);
break;
case desc:
break;
}
}
}
public SonosMetaData getMetaData() {
return new SonosMetaData(id, parentId, resource.toString(), streamContent.toString(),
albumArtUri.toString(), title.toString(), upnpClass.toString(), creator.toString(),
album.toString(), albumArtist.toString());
}
}
static private class RenderingControlEventHandler extends DefaultHandler {
private final Map<String, String> changes = new HashMap<String, String>();
private boolean getPresetName = false;
private String presetName;
@Override
public void startElement(String uri, String localName, String qName, Attributes atts) throws SAXException {
if ("Volume".equals(qName)) {
changes.put(qName + atts.getValue("channel"), atts.getValue("val"));
} else if ("Mute".equals(qName)) {
changes.put(qName + atts.getValue("channel"), atts.getValue("val"));
} else if ("Bass".equals(qName)) {
changes.put(qName, atts.getValue("val"));
} else if ("Treble".equals(qName)) {
changes.put(qName, atts.getValue("val"));
} else if ("Loudness".equals(qName)) {
changes.put(qName + atts.getValue("channel"), atts.getValue("val"));
} else if ("OutputFixed".equals(qName)) {
changes.put(qName, atts.getValue("val"));
} else if ("PresetNameList".equals(qName)) {
getPresetName = true;
}
}
@Override
public void characters(char[] ch, int start, int length) throws SAXException {
if (getPresetName) {
presetName = new String(ch, start, length);
}
}
@Override
public void endElement(String uri, String localName, String qName) throws SAXException {
if (getPresetName) {
getPresetName = false;
changes.put(qName, presetName);
}
}
public Map<String, String> getChanges() {
return changes;
}
}
public static String getRoomName(String descriptorXML) {
RoomNameHandler roomNameHandler = new RoomNameHandler();
try {
XMLReader reader = XMLReaderFactory.createXMLReader();
reader.setContentHandler(roomNameHandler);
URL url = new URL(descriptorXML);
reader.parse(new InputSource(url.openStream()));
} catch (IOException | SAXException e) {
logger.error("Could not parse Sonos room name from string '{}'", descriptorXML);
}
return roomNameHandler.getRoomName();
}
static private class RoomNameHandler extends DefaultHandler {
private String roomName;
private boolean roomNameTag;
@Override
public void startElement(String uri, String localName, String qName, Attributes atts) throws SAXException {
if ("roomName".equalsIgnoreCase(localName)) {
roomNameTag = true;
}
}
@Override
public void characters(char[] ch, int start, int length) throws SAXException {
if (roomNameTag) {
roomName = new String(ch, start, length);
roomNameTag = false;
}
}
public String getRoomName() {
return roomName;
}
}
public static String parseModelDescription(URL descriptorURL) {
ModelNameHandler modelNameHandler = new ModelNameHandler();
try {
XMLReader reader = XMLReaderFactory.createXMLReader();
reader.setContentHandler(modelNameHandler);
URL url = new URL(descriptorURL.toString());
reader.parse(new InputSource(url.openStream()));
} catch (IOException | SAXException e) {
logger.error("Could not parse Sonos model name from string '{}'", descriptorURL.toString());
}
return modelNameHandler.getModelName();
}
static private class ModelNameHandler extends DefaultHandler {
private String modelName;
private boolean modelNameTag;
@Override
public void startElement(String uri, String localName, String qName, Attributes atts) throws SAXException {
if ("modelName".equalsIgnoreCase(localName)) {
modelNameTag = true;
}
}
@Override
public void characters(char[] ch, int start, int length) throws SAXException {
if (modelNameTag) {
modelName = new String(ch, start, length);
modelNameTag = false;
}
}
public String getModelName() {
return modelName;
}
}
/**
* The model name provided by upnp is formated like in the example form "Sonos PLAY:1" or "Sonos PLAYBAR"
*
* @param sonosModelName Sonos model name provided via upnp device
* @return the extracted players model name without column (:) character used for ThingType creation
*/
public static String extractModelName(String sonosModelName) {
Matcher matcher = Pattern.compile("\\s(.*)").matcher(sonosModelName);
if (matcher.find()) {
sonosModelName = matcher.group(1);
}
if (sonosModelName.contains(":")) {
sonosModelName = sonosModelName.replace(":", "");
}
return sonosModelName;
}
public static String compileMetadataString(SonosEntry entry) {
/**
* If the entry contains resource meta data we will override this with
* that data.
*/
String id = entry.getId();
String parentId = entry.getParentId();
String title = entry.getTitle();
String upnpClass = entry.getUpnpClass();
/**
* By default 'RINCON_AssociatedZPUDN' is used for most operations,
* however when playing a favorite entry that is associated withh a
* subscription like pandora we need to use the desc string asscoiated
* with that item.
*/
String desc = "RINCON_AssociatedZPUDN";
/**
* If resource meta data exists, use it over the parent data
*/
if (entry.getResourceMetaData() != null) {
id = entry.getResourceMetaData().getId();
parentId = entry.getResourceMetaData().getParentId();
title = entry.getResourceMetaData().getTitle();
desc = entry.getResourceMetaData().getDesc();
upnpClass = entry.getResourceMetaData().getUpnpClass();
}
String metadata = METADATA_FORMAT.format(new Object[] { id, parentId, title, upnpClass, desc });
return metadata;
}
}
|
package org.glyptodon.guacamole.auth.jdbc.user;
import com.google.inject.Inject;
import com.google.inject.Provider;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import javax.servlet.http.HttpServletRequest;
import org.glyptodon.guacamole.net.auth.Credentials;
import org.glyptodon.guacamole.auth.jdbc.base.ModeledDirectoryObjectMapper;
import org.glyptodon.guacamole.auth.jdbc.base.ModeledDirectoryObjectService;
import org.glyptodon.guacamole.GuacamoleClientException;
import org.glyptodon.guacamole.GuacamoleException;
import org.glyptodon.guacamole.GuacamoleUnsupportedException;
import org.glyptodon.guacamole.auth.jdbc.permission.ObjectPermissionMapper;
import org.glyptodon.guacamole.auth.jdbc.permission.ObjectPermissionModel;
import org.glyptodon.guacamole.auth.jdbc.permission.UserPermissionMapper;
import org.glyptodon.guacamole.auth.jdbc.security.PasswordEncryptionService;
import org.glyptodon.guacamole.form.Field;
import org.glyptodon.guacamole.form.PasswordField;
import org.glyptodon.guacamole.net.auth.AuthenticationProvider;
import org.glyptodon.guacamole.net.auth.User;
import org.glyptodon.guacamole.net.auth.credentials.CredentialsInfo;
import org.glyptodon.guacamole.net.auth.credentials.GuacamoleInsufficientCredentialsException;
import org.glyptodon.guacamole.net.auth.permission.ObjectPermission;
import org.glyptodon.guacamole.net.auth.permission.ObjectPermissionSet;
import org.glyptodon.guacamole.net.auth.permission.SystemPermission;
import org.glyptodon.guacamole.net.auth.permission.SystemPermissionSet;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Service which provides convenience methods for creating, retrieving, and
* manipulating users.
*
* @author Michael Jumper, James Muehlner
*/
public class UserService extends ModeledDirectoryObjectService<ModeledUser, User, UserModel> {
/**
* Logger for this class.
*/
private static final Logger logger = LoggerFactory.getLogger(UserService.class);
private static final ObjectPermission.Type[] IMPLICIT_USER_PERMISSIONS = {
ObjectPermission.Type.READ,
ObjectPermission.Type.UPDATE
};
/**
* The name of the HTTP password parameter to expect if the user is
* changing their expired password upon login.
*/
private static final String NEW_PASSWORD_PARAMETER = "new-password";
/**
* The password field to provide the user when their password is expired
* and must be changed.
*/
private static final Field NEW_PASSWORD = new PasswordField(NEW_PASSWORD_PARAMETER);
/**
* The name of the HTTP password confirmation parameter to expect if the
* user is changing their expired password upon login.
*/
private static final String CONFIRM_NEW_PASSWORD_PARAMETER = "confirm-new-password";
/**
* The password confirmation field to provide the user when their password
* is expired and must be changed.
*/
private static final Field CONFIRM_NEW_PASSWORD = new PasswordField(CONFIRM_NEW_PASSWORD_PARAMETER);
/**
* Information describing the expected credentials if a user's password is
* expired. If a user's password is expired, it must be changed during the
* login process.
*/
private static final CredentialsInfo EXPIRED_PASSWORD = new CredentialsInfo(Arrays.asList(
CredentialsInfo.USERNAME,
CredentialsInfo.PASSWORD,
NEW_PASSWORD,
CONFIRM_NEW_PASSWORD
));
/**
* Mapper for accessing users.
*/
@Inject
private UserMapper userMapper;
@Inject
private UserPermissionMapper userPermissionMapper;
/**
* Provider for creating users.
*/
@Inject
private Provider<ModeledUser> userProvider;
/**
* Service for hashing passwords.
*/
@Inject
private PasswordEncryptionService encryptionService;
@Override
protected ModeledDirectoryObjectMapper<UserModel> getObjectMapper() {
return userMapper;
}
@Override
protected ObjectPermissionMapper getPermissionMapper() {
return userPermissionMapper;
}
@Override
protected ModeledUser getObjectInstance(AuthenticatedUser currentUser,
UserModel model) {
ModeledUser user = userProvider.get();
user.init(currentUser, model);
return user;
}
@Override
protected UserModel getModelInstance(AuthenticatedUser currentUser,
final User object) {
// Create new ModeledUser backed by blank model
UserModel model = new UserModel();
ModeledUser user = getObjectInstance(currentUser, model);
// Set model contents through ModeledUser, copying the provided user
user.setIdentifier(object.getIdentifier());
user.setPassword(object.getPassword());
return model;
}
@Override
protected boolean hasCreatePermission(AuthenticatedUser user)
throws GuacamoleException {
SystemPermissionSet permissionSet = user.getUser().getSystemPermissions();
return permissionSet.hasPermission(SystemPermission.Type.CREATE_USER);
}
@Override
protected ObjectPermissionSet getPermissionSet(AuthenticatedUser user)
throws GuacamoleException {
return user.getUser().getUserPermissions();
}
@Override
protected void beforeCreate(AuthenticatedUser user, UserModel model)
throws GuacamoleException {
super.beforeCreate(user, model);
// Username must not be blank
if (model.getIdentifier() == null || model.getIdentifier().trim().isEmpty())
throw new GuacamoleClientException("The username must not be blank.");
// Do not create duplicate users
Collection<UserModel> existing = userMapper.select(Collections.singleton(model.getIdentifier()));
if (!existing.isEmpty())
throw new GuacamoleClientException("User \"" + model.getIdentifier() + "\" already exists.");
}
@Override
protected void beforeUpdate(AuthenticatedUser user,
UserModel model) throws GuacamoleException {
super.beforeUpdate(user, model);
// Username must not be blank
if (model.getIdentifier() == null || model.getIdentifier().trim().isEmpty())
throw new GuacamoleClientException("The username must not be blank.");
// Check whether such a user is already present
UserModel existing = userMapper.selectOne(model.getIdentifier());
if (existing != null) {
// Do not rename to existing user
if (!existing.getObjectID().equals(model.getObjectID()))
throw new GuacamoleClientException("User \"" + model.getIdentifier() + "\" already exists.");
}
}
@Override
protected Collection<ObjectPermissionModel>
getImplicitPermissions(AuthenticatedUser user, UserModel model) {
Collection<ObjectPermissionModel> implicitPermissions = super.getImplicitPermissions(user, model);
for (ObjectPermission.Type permissionType : IMPLICIT_USER_PERMISSIONS) {
ObjectPermissionModel permissionModel = new ObjectPermissionModel();
permissionModel.setUserID(model.getObjectID());
permissionModel.setUsername(model.getIdentifier());
permissionModel.setType(permissionType);
permissionModel.setObjectIdentifier(model.getIdentifier());
implicitPermissions.add(permissionModel);
}
return implicitPermissions;
}
@Override
protected void beforeDelete(AuthenticatedUser user, String identifier) throws GuacamoleException {
super.beforeDelete(user, identifier);
// Do not allow users to delete themselves
if (identifier.equals(user.getUser().getIdentifier()))
throw new GuacamoleUnsupportedException("Deleting your own user is not allowed.");
}
/**
* Retrieves the user corresponding to the given credentials from the
* database. If the user account is expired, and the credentials contain
* the necessary additional parameters to reset the user's password, the
* password is reset.
*
* @param authenticationProvider
* The AuthenticationProvider on behalf of which the user is being
* retrieved.
*
* @param credentials
* The credentials to use when locating the user.
*
* @return
* An AuthenticatedUser containing the existing ModeledUser object if
* the credentials given are valid, null otherwise.
*
* @throws GuacamoleException
* If the provided credentials to not conform to expectations.
*/
public AuthenticatedUser retrieveAuthenticatedUser(AuthenticationProvider authenticationProvider,
Credentials credentials) throws GuacamoleException {
// Get username and password
String username = credentials.getUsername();
String password = credentials.getPassword();
// Retrieve corresponding user model, if such a user exists
UserModel userModel = userMapper.selectOne(username);
if (userModel == null)
return null;
// If user is disabled, pretend user does not exist
if (userModel.isDisabled())
return null;
// Verify provided password is correct
byte[] hash = encryptionService.createPasswordHash(password, userModel.getPasswordSalt());
if (!Arrays.equals(hash, userModel.getPasswordHash()))
return null;
// Create corresponding user object, set up cyclic reference
ModeledUser user = getObjectInstance(null, userModel);
user.setCurrentUser(new AuthenticatedUser(authenticationProvider, user, credentials));
// Verify user account is still valid as of today
if (!user.isAccountValid())
throw new GuacamoleClientException("LOGIN.ERROR_NOT_VALID");
// Verify user account is allowed to be used at the current time
if (!user.isAccountAccessible())
throw new GuacamoleClientException("LOGIN.ERROR_NOT_ACCESSIBLE");
// Update password if password is expired
if (userModel.isExpired()) {
// Pull new password from HTTP request
HttpServletRequest request = credentials.getRequest();
String newPassword = request.getParameter(NEW_PASSWORD_PARAMETER);
String confirmNewPassword = request.getParameter(CONFIRM_NEW_PASSWORD_PARAMETER);
// Require new password if account is expired
if (newPassword == null || confirmNewPassword == null) {
logger.info("The password of user \"{}\" has expired and must be reset.", username);
throw new GuacamoleInsufficientCredentialsException("LOGIN.INFO_PASSWORD_EXPIRED", EXPIRED_PASSWORD);
}
// New password must be different from old password
if (newPassword.equals(credentials.getPassword()))
throw new GuacamoleClientException("LOGIN.ERROR_PASSWORD_SAME");
// New password must not be blank
if (newPassword.isEmpty())
throw new GuacamoleClientException("LOGIN.ERROR_PASSWORD_BLANK");
// Confirm that the password was entered correctly twice
if (!newPassword.equals(confirmNewPassword))
throw new GuacamoleClientException("LOGIN.ERROR_PASSWORD_MISMATCH");
// Change password and reset expiration flag
userModel.setExpired(false);
user.setPassword(newPassword);
userMapper.update(userModel);
logger.info("Expired password of user \"{}\" has been reset.", username);
}
// Return now-authenticated user
return user.getCurrentUser();
}
/**
* Retrieves the user corresponding to the given AuthenticatedUser from the
* database.
*
* @param authenticatedUser
* The AuthenticatedUser to retrieve the corresponding ModeledUser of.
*
* @return
* The ModeledUser which corresponds to the given AuthenticatedUser, or
* null if no such user exists.
*/
public ModeledUser retrieveUser(org.glyptodon.guacamole.net.auth.AuthenticatedUser authenticatedUser) {
// If we already queried this user, return that rather than querying again
if (authenticatedUser instanceof AuthenticatedUser)
return ((AuthenticatedUser) authenticatedUser).getUser();
// Get username
String username = authenticatedUser.getIdentifier();
// Retrieve corresponding user model, if such a user exists
UserModel userModel = userMapper.selectOne(username);
if (userModel == null)
return null;
// Create corresponding user object, set up cyclic reference
ModeledUser user = getObjectInstance(null, userModel);
user.setCurrentUser(new AuthenticatedUser(authenticatedUser.getAuthenticationProvider(), user, authenticatedUser.getCredentials()));
// Return already-authenticated user
return user;
}
}
|
package org.innovateuk.ifs.publiccontent.controller;
import org.innovateuk.ifs.publiccontent.viewmodel.AbstractPublicContentViewModel;
/**
* Subclass of {@link AbstractPublicContentViewModel} used as a type parameter when testing subclasses of
* {@link AbstractPublicContentSectionController} in {@link AbstractContentGroupControllerTest} and
* {@link AbstractPublicContentSectionControllerTest}.
*/
class TestPublicContentViewModel extends AbstractPublicContentViewModel {
}
|
package com.atlassian.jira.plugins.dvcs.sync;
import com.atlassian.jira.plugins.dvcs.activity.RepositoryPullRequestDao;
import com.atlassian.jira.plugins.dvcs.activity.RepositoryPullRequestMapping;
import com.atlassian.jira.plugins.dvcs.dao.RepositoryDao;
import com.atlassian.jira.plugins.dvcs.model.Message;
import com.atlassian.jira.plugins.dvcs.model.Participant;
import com.atlassian.jira.plugins.dvcs.model.Progress;
import com.atlassian.jira.plugins.dvcs.model.Repository;
import com.atlassian.jira.plugins.dvcs.service.PullRequestService;
import com.atlassian.jira.plugins.dvcs.service.message.MessagingService;
import com.atlassian.jira.plugins.dvcs.spi.bitbucket.BitbucketClientBuilder;
import com.atlassian.jira.plugins.dvcs.spi.bitbucket.BitbucketClientBuilderFactory;
import com.atlassian.jira.plugins.dvcs.spi.bitbucket.clientlibrary.client.BitbucketRemoteClient;
import com.atlassian.jira.plugins.dvcs.spi.bitbucket.clientlibrary.model.BitbucketBranch;
import com.atlassian.jira.plugins.dvcs.spi.bitbucket.clientlibrary.model.BitbucketLink;
import com.atlassian.jira.plugins.dvcs.spi.bitbucket.clientlibrary.model.BitbucketLinks;
import com.atlassian.jira.plugins.dvcs.spi.bitbucket.clientlibrary.model.BitbucketPullRequest;
import com.atlassian.jira.plugins.dvcs.spi.bitbucket.clientlibrary.model.BitbucketPullRequestActivityInfo;
import com.atlassian.jira.plugins.dvcs.spi.bitbucket.clientlibrary.model.BitbucketPullRequestBaseActivity;
import com.atlassian.jira.plugins.dvcs.spi.bitbucket.clientlibrary.model.BitbucketPullRequestHead;
import com.atlassian.jira.plugins.dvcs.spi.bitbucket.clientlibrary.model.BitbucketPullRequestPage;
import com.atlassian.jira.plugins.dvcs.spi.bitbucket.clientlibrary.model.BitbucketPullRequestParticipant;
import com.atlassian.jira.plugins.dvcs.spi.bitbucket.clientlibrary.model.BitbucketPullRequestRepository;
import com.atlassian.jira.plugins.dvcs.spi.bitbucket.clientlibrary.request.BitbucketRequestException;
import com.atlassian.jira.plugins.dvcs.spi.bitbucket.clientlibrary.request.RemoteRequestor;
import com.atlassian.jira.plugins.dvcs.spi.bitbucket.clientlibrary.request.ResponseCallback;
import com.atlassian.jira.plugins.dvcs.spi.bitbucket.clientlibrary.restpoints.PullRequestRemoteRestpoint;
import com.atlassian.jira.plugins.dvcs.spi.bitbucket.message.BitbucketSynchronizeActivityMessage;
import com.google.common.collect.Lists;
import org.mockito.ArgumentCaptor;
import org.mockito.Captor;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.MockitoAnnotations;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import java.util.Collections;
import java.util.Date;
import java.util.Map;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.anyInt;
import static org.mockito.Matchers.anyMap;
import static org.mockito.Matchers.anyString;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import static org.testng.Assert.assertNull;
import static org.testng.Assert.assertTrue;
/**
* Test
*/
public class BitbucketSynchronizeActivityMessageConsumerTest
{
@Mock
private MessagingService messagingService;
@Mock
private BitbucketClientBuilderFactory bitbucketClientBuilderFactory;
@Mock
private RepositoryPullRequestDao repositoryPullRequestDao;
@Mock
private PullRequestService pullRequestService;
@Mock
private RepositoryDao repositoryDao;
@InjectMocks
private BitbucketSynchronizeActivityMessageConsumer testedClass;
@Mock
private Progress progress;
@Mock
private Repository repository;
@Mock
private BitbucketRemoteClient bitbucketRemoteClient;
@Mock
private BitbucketRemoteClient cachedBitbucketRemoteClient;
@Mock
private RemoteRequestor requestor;
@Mock
private RemoteRequestor cachedRequestor;
@Mock
private BitbucketPullRequest bitbucketPullRequest;
@Mock
private BitbucketSynchronizeActivityMessage payload;
@Mock
private Message<BitbucketSynchronizeActivityMessage> message;
@Captor
private ArgumentCaptor<Map> savePullRequestCaptor;
@Captor
private ArgumentCaptor<Map<String, Participant>> participantsIndexCaptor;
private class BuilderAnswer implements Answer<Object>
{
private boolean cached;
@Override
public Object answer(InvocationOnMock invocation) throws Throwable
{
Object builderMock = invocation.getMock();
if (invocation.getMethod().getReturnType().isInstance(builderMock))
{
if (invocation.getMethod().getName().equals("cached"))
{
cached = true;
}
return builderMock;
} else
{
return cached ? cachedBitbucketRemoteClient : bitbucketRemoteClient;
}
}
}
@BeforeMethod
private void init()
{
testedClass = null;
MockitoAnnotations.initMocks(this);
when(repository.getOrgName()).thenReturn("org");
when(repository.getSlug()).thenReturn("repo");
when(bitbucketPullRequest.getId()).thenReturn(1L);
when(bitbucketPullRequest.getUpdatedOn()).thenReturn(new Date());
when(bitbucketRemoteClient.getPullRequestAndCommentsRemoteRestpoint()).thenReturn(new PullRequestRemoteRestpoint(requestor));
when(cachedBitbucketRemoteClient.getPullRequestAndCommentsRemoteRestpoint()).thenReturn(new PullRequestRemoteRestpoint(cachedRequestor));
BitbucketPullRequestPage<BitbucketPullRequestActivityInfo> activityPage = Mockito.mock(BitbucketPullRequestPage.class);
String activityUrl = String.format("/repositories/%s/%s/pullrequests/activity?pagelen=%s&page=", repository.getOrgName(), repository.getSlug(), PullRequestRemoteRestpoint.REPO_ACTIVITY_PAGESIZE);
String pullRequestDetailUrl = String.format("/repositories/%s/%s/pullrequests/%s", repository.getOrgName(), repository.getSlug(), bitbucketPullRequest.getId());
when(requestor.get(Mockito.startsWith(activityUrl), anyMap(), any(ResponseCallback.class))).thenReturn(activityPage);
when(requestor.get(eq(pullRequestDetailUrl), anyMap(), any(ResponseCallback.class))).thenReturn(bitbucketPullRequest);
when(cachedRequestor.get(Mockito.startsWith(activityUrl), anyMap(), any(ResponseCallback.class))).thenReturn(activityPage);
when(cachedRequestor.get(eq(pullRequestDetailUrl), anyMap(), any(ResponseCallback.class))).thenReturn(bitbucketPullRequest);
BitbucketPullRequestActivityInfo activityInfo = Mockito.mock(BitbucketPullRequestActivityInfo.class);
when(activityPage.getValues()).thenReturn(Lists.newArrayList(activityInfo));
BitbucketPullRequestBaseActivity activity = Mockito.mock(BitbucketPullRequestBaseActivity.class);
when(activityInfo.getActivity()).thenReturn(activity);
when(activity.getDate()).thenReturn(new Date());
when(activity.getUpdatedOn()).thenReturn(new Date());
when(activityInfo.getPullRequest()).thenReturn(bitbucketPullRequest);
BitbucketLinks bitbucketLinks = Mockito.mock(BitbucketLinks.class);
when(bitbucketPullRequest.getLinks()).thenReturn(bitbucketLinks);
when(bitbucketClientBuilderFactory.forRepository(repository)).then(new Answer<BitbucketClientBuilder>()
{
@Override
public BitbucketClientBuilder answer(final InvocationOnMock invocation) throws Throwable
{
BuilderAnswer builderAnswer = new BuilderAnswer();
BitbucketClientBuilder bitbucketClientBuilder = mock(BitbucketClientBuilder.class, builderAnswer);
return bitbucketClientBuilder;
}
});
when(payload.getProgress()).thenReturn(progress);
when(payload.getRepository()).thenReturn(repository);
when(payload.getPageNum()).thenReturn(1);
RepositoryPullRequestMapping pullRequestMapping = Mockito.mock(RepositoryPullRequestMapping.class);
Date updatedOn = bitbucketPullRequest.getUpdatedOn();
long remoteId = bitbucketPullRequest.getId();
when(pullRequestMapping.getUpdatedOn()).thenReturn(updatedOn);
when(pullRequestMapping.getRemoteId()).thenReturn(remoteId);
when(repositoryPullRequestDao.savePullRequest(eq(repository), savePullRequestCaptor.capture())).thenReturn(pullRequestMapping);
BitbucketLinks links = mockLinks();
when(bitbucketPullRequest.getLinks()).thenReturn(links);
}
@Test
public void testSourceBranchDeleted()
{
BitbucketPullRequestHead source = Mockito.mock(BitbucketPullRequestHead.class);
when(source.getRepository()).thenReturn(Mockito.mock(BitbucketPullRequestRepository.class));
when(source.getBranch()).thenReturn(null);
when(bitbucketPullRequest.getSource()).thenReturn(source);
testedClass.onReceive(message, payload);
verify(repositoryPullRequestDao, never()).updatePullRequestInfo(anyInt(), anyString(), anyString(), anyString(), any(RepositoryPullRequestMapping.Status.class), any(Date.class), anyString(), anyInt());
verify(repositoryPullRequestDao, never()).savePullRequest(eq(repository), any(Map.class));
}
@Test
public void testSourceRepositoryDeleted()
{
when(bitbucketPullRequest.getSource()).thenReturn(null);
testedClass.onReceive(message, payload);
verify(repositoryPullRequestDao, never()).updatePullRequestInfo(anyInt(), anyString(), anyString(), anyString(), any(RepositoryPullRequestMapping.Status.class), any(Date.class), anyString(), anyInt());
verify(repositoryPullRequestDao, never()).savePullRequest(eq(repository), any(Map.class));
}
@Test(expectedExceptions = BitbucketRequestException.Unauthorized_401.class)
public void testAccessDenied()
{
when(requestor.get(anyString(), anyMap(), any(ResponseCallback.class))).thenThrow(new BitbucketRequestException.Unauthorized_401());
when(cachedRequestor.get(anyString(), anyMap(), any(ResponseCallback.class))).thenThrow(new BitbucketRequestException.Unauthorized_401());
testedClass.onReceive(message, payload);
}
@Test(expectedExceptions = BitbucketRequestException.NotFound_404.class)
public void testNotFound()
{
when(requestor.get(anyString(), anyMap(), any(ResponseCallback.class))).thenThrow(new BitbucketRequestException.NotFound_404());
when(cachedRequestor.get(anyString(), anyMap(), any(ResponseCallback.class))).thenThrow(new BitbucketRequestException.NotFound_404());
testedClass.onReceive(message, payload);
}
@Test(expectedExceptions = BitbucketRequestException.InternalServerError_500.class)
public void testInternalServerError()
{
when(requestor.get(anyString(), anyMap(), any(ResponseCallback.class))).thenThrow(new BitbucketRequestException.InternalServerError_500());
when(cachedRequestor.get(anyString(), anyMap(), any(ResponseCallback.class))).thenThrow(new BitbucketRequestException.InternalServerError_500());
testedClass.onReceive(message, payload);
}
@Test
public void testNoAuthor()
{
BitbucketPullRequestHead source = mockRef("branch");
BitbucketPullRequestHead destination = mockRef("master");
when(bitbucketPullRequest.getSource()).thenReturn(source);
when(bitbucketPullRequest.getDestination()).thenReturn(destination);
when(bitbucketPullRequest.getAuthor()).thenReturn(null);
testedClass.onReceive(message, payload);
assertNull(savePullRequestCaptor.getValue().get(RepositoryPullRequestMapping.AUTHOR));
}
@Test
public void testNoParticipants()
{
BitbucketPullRequestHead source = mockRef("branch");
BitbucketPullRequestHead destination = mockRef("master");
when(bitbucketPullRequest.getSource()).thenReturn(source);
when(bitbucketPullRequest.getDestination()).thenReturn(destination);
when(bitbucketPullRequest.getParticipants()).thenReturn(Collections.<BitbucketPullRequestParticipant>emptyList());
testedClass.onReceive(message, payload);
verify(pullRequestService).updatePullRequestParticipants(anyInt(), anyInt(), participantsIndexCaptor.capture());
assertTrue(participantsIndexCaptor.getValue().isEmpty());
}
@Test
public void testCacheOnlyFirstPage()
{
BitbucketPullRequestHead source = mockRef("branch");
BitbucketPullRequestHead destination = mockRef("master");
when(bitbucketPullRequest.getSource()).thenReturn(source);
when(bitbucketPullRequest.getDestination()).thenReturn(destination);
when(payload.getPageNum()).thenReturn(1);
testedClass.onReceive(message, payload);
verify(cachedRequestor, times(1)).get(anyString(), anyMap(), any(ResponseCallback.class));
}
@Test
public void testNoCacheSecondPage()
{
BitbucketPullRequestHead source = mockRef("branch");
BitbucketPullRequestHead destination = mockRef("master");
when(bitbucketPullRequest.getSource()).thenReturn(source);
when(bitbucketPullRequest.getDestination()).thenReturn(destination);
when(payload.getPageNum()).thenReturn(2);
testedClass.onReceive(message, payload);
verify(cachedRequestor, never()).get(anyString(), anyMap(), any(ResponseCallback.class));
}
private BitbucketLinks mockLinks()
{
BitbucketLinks bitbucketLinks = new BitbucketLinks();
BitbucketLink htmlLink = new BitbucketLink();
bitbucketLinks.setHtml(htmlLink);
return bitbucketLinks;
}
private BitbucketPullRequestHead mockRef(String branchName)
{
BitbucketPullRequestHead source = Mockito.mock(BitbucketPullRequestHead.class);
BitbucketBranch bitbucketBranch = new BitbucketBranch();
bitbucketBranch.setName(branchName);
when(source.getRepository()).thenReturn(Mockito.mock(BitbucketPullRequestRepository.class));
when(source.getBranch()).thenReturn(bitbucketBranch);
return source;
}
}
|
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.AbstractButton;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTree;
import javax.swing.tree.DefaultMutableTreeNode;
import org.pathvisio.data.DataException;
import org.pathvisio.model.ConverterException;
public class TestFrames {
private static Set<String> genidInPway = new HashSet<String>();
/**
* @param args
*/
public static void main(String[] args) throws DataException, ConverterException{
// create a new frame
JFrame frame = new JFrame("GOTerm Distribution");
// When click on exit, exit the frame
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// set the size of the frame
frame.setSize(350,570);
// create a new panel
JPanel canvasButtons = new JPanel();
// create two new buttons, using the makeButton method
JButton calcButton = makeButton("Calculate");
JButton closeButton = makeButton("Close");
// add the functionality to the close button
closeButton.addActionListener(
new ActionListener(){
public void actionPerformed(ActionEvent ae){
System.exit(0);
}
}
);
// add the functionality to the calculate button
calcButton.addActionListener(
new ActionListener(){
public void actionPerformed(ActionEvent ae){
System.out.println("Calculate Button pressed");
}
}
);
// add the buttons to the canvas
canvasButtons.add(calcButton);
canvasButtons.add(closeButton);
// add the canvas to the frame
frame.add(canvasButtons, BorderLayout.SOUTH);
// create a new panel
JPanel canvasTree = new JPanel();
// create a tree
DefaultMutableTreeNode top = TreeReader();
JTree tree = new JTree(top);
// create a scroll pane
JScrollPane scrollPane = new JScrollPane(tree);
Dimension scrollPaneSize = new Dimension(315,485);
scrollPane.setPreferredSize(scrollPaneSize);
canvasTree.add(scrollPane);
frame.add(canvasTree, BorderLayout.NORTH);
// Show the frame
frame.setVisible(true);
}
/**
* create a new JButton of a preferred size, and with the text centered.
*/
public static JButton makeButton(String name){
// create a new button
JButton button = new JButton(name);
// set the size of the button
Dimension sizeButton = new Dimension(130,30);
button.setPreferredSize(sizeButton);
// center the text (horizontally and vertically) in the button
button.setVerticalTextPosition(AbstractButton.CENTER);
button.setHorizontalTextPosition(AbstractButton.CENTER);
// return the button
return button;
}
public static DefaultMutableTreeNode TreeReader() throws DataException, ConverterException{
DefaultMutableTreeNode top = new DefaultMutableTreeNode("GOTerm Distribution");
// read all GoTerms
Set<GoTerm> terms = new HashSet<GoTerm>();
terms = GoReader.readGoDatabase("C:\\gene_ontology.obo");
// get the Roots of the GoTerms
Set<GoTerm> roots= new HashSet<GoTerm>();
roots=GoReader.getRoots(terms);
terms = addGenes(terms);
genidInPway = getN.getSetGenIdsInPways("C:\\databases\\Rn_39_34i.pgdb", "C:\\WPClient\\Rattus_norvegicus");
top = makeTree(roots, terms, top, "r");
return top;
}
public static DefaultMutableTreeNode makeTree(Set<GoTerm> parents, Set<GoTerm> allTerms, DefaultMutableTreeNode top, String level){
// loop trough all given GoTerms
for(GoTerm parent : parents){
// create a new parent branch
DefaultMutableTreeNode par = new DefaultMutableTreeNode(parent.getName() + " " +
"<m:"+parent.getNumberOfGenes()+", n:"+parent.getOverlapGenes(genidInPway)+">");
// add the new parent to the top structure
top.add(par);
// make a list of all children
Set<GoTerm> children = new HashSet<GoTerm>();
children = parent.getChildren();
// if a children list is not empty, set the children as new parents, and put them in
// this method again
if(!children.isEmpty()){
// give some output to show where you are
//System.out.println("mk Tree "+level);
// set the maximum level of children
//if (level.length() < 4){
// create a new tree and add it; when an error occures, catch it
DefaultMutableTreeNode childrenNodes = makeTree(children, allTerms, par, level+"*");
try{
par.add(childrenNodes);
}
catch(IllegalArgumentException e) {
System.out.println("kind is voorouder"); // deze error komt steeds als je een stapje naar beneden gaat.
}
}
}
return top;
}
public static Set<GoTerm> addGenes(Set<GoTerm> terms){
// create a new map; the key is the GoTerm's id, the set of strings are the gene strings
Map<String,Set<String>> geneByGO=genesGOid.geneByGO(genesGOid.goByGene(genesGOid.readDatabase("C:\\mart_export1.txt")));
for (GoTerm term: terms){
Set<String> genes = new HashSet<String>();
try{
genes = geneByGO.get(term.getId());
for (String gene : genes){
term.addGene(gene);
}
}
catch (NullPointerException e){
System.out.println("set is leeg");
}
}
return terms;
}
}
|
package com.github.j5ik2o.ddd_example.domain;
import com.github.j5ik2o.ddd_eaxmple.utils.IdGenerator;
import com.google.common.collect.Lists;
import lombok.NonNull;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
public final class BankAccount {
@NonNull
private Long id;
@NonNull
private List<BankAccountEvent> events;
@NonNull
public Long getId() {
return this.id;
}
@NonNull
public List<BankAccountEvent> getEvents() {
return cloneList(this.events);
}
private BankAccount(Long id, List<BankAccountEvent> events) {
this.id = id;
if (getBalanceByEvents(events).isLessThan(BigDecimal.ZERO)) {
throw new IllegalArgumentException("total money is less than zero!");
}
this.events = cloneList(events);
}
private List<BankAccountEvent> cloneList(List<BankAccountEvent> events) {
ArrayList<BankAccountEvent> result = Lists.newArrayListWithCapacity(events.size());
for (BankAccountEvent event : events) {
result.add(event);
}
return result;
}
private BankAccount addBankAccountEvent(Long toBankAccountId, Long fromBankAccountId, Money money) {
Long eventId = IdGenerator.generateId();
return addBankAccountEvent(BankAccountEvent.of(eventId, id, null, money));
}
private BankAccount addBankAccountEvent(BankAccountEvent event) {
List<BankAccountEvent> result = Lists.newArrayList(events);
result.add(event);
return of(id, result);
}
/**
*
*
* @param money
* @return
*/
public BankAccount depositCash(Money money) {
return addBankAccountEvent(id, null, money);
}
/**
*
*
* @param money
* @return
*/
public BankAccount withdrawCash(Money money) {
return addBankAccountEvent(null, id, money.negated());
}
/**
*
*
* @param from
* @param money
* @return
*/
public BankAccount depositFrom(BankAccount from, Money money) {
return addBankAccountEvent(id, from.getId(), money);
}
/**
*
*
* @param to
* @param money
* @return
*/
public BankAccount withdrawTo(BankAccount to, Money money) {
return addBankAccountEvent(to.getId(), id, money.negated());
}
/**
*
*
* @return
*/
public Money getBalance() {
return getBalanceByEvents(events);
}
public static BankAccount of(Long id, List<BankAccountEvent> events) {
return new BankAccount(id, events);
}
public static BankAccount of(Long id) {
return of(id, Lists.newArrayList());
}
private static Money getBalanceByEvents(List<BankAccountEvent> events) {
return getTotalAmountByMonies(getMonies(events));
}
private static Money getTotalAmountByMonies(List<Money> monies) {
return Money.sum(monies);
}
private static List<Money> getMonies(List<BankAccountEvent> events) {
List<Money> result = Lists.newArrayList();
for (BankAccountEvent event : events) {
result.add(event.getMoney());
}
return result;
}
public boolean equals(Object o) {
if (o == this) return true;
if (!(o instanceof BankAccount)) return false;
final BankAccount other = (BankAccount) o;
final Object this$id = this.getId();
final Object other$id = other.getId();
if (this$id == null ? other$id != null : !this$id.equals(other$id)) return false;
final Object this$events = this.getEvents();
final Object other$events = other.getEvents();
if (this$events == null ? other$events != null : !this$events.equals(other$events)) return false;
return true;
}
public int hashCode() {
final int PRIME = 59;
int result = 1;
final Object $id = this.getId();
result = result * PRIME + ($id == null ? 43 : $id.hashCode());
final Object $events = this.getEvents();
result = result * PRIME + ($events == null ? 43 : $events.hashCode());
return result;
}
public String toString() {
return "com.github.j5ik2o.ddd_example.domain.BankAccount(id=" + this.getId() + ", events=" + this.getEvents() + ")";
}
}
|
package org.drools.reteoo;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.drools.common.InternalFactHandle;
import org.drools.common.InternalWorkingMemory;
import org.drools.spi.PropagationContext;
import org.drools.util.LinkedList;
import org.drools.util.LinkedListObjectWrapper;
public class CompositeTupleSinkAdapter implements TupleSinkPropagator {
private TupleSinkNodeList sinks;
public CompositeTupleSinkAdapter() {
this.sinks = new TupleSinkNodeList();
}
public void addTupleSink(TupleSink sink) {
this.sinks.add( (TupleSinkNode) sink );
}
public void removeTupleSink(TupleSink sink) {
this.sinks.remove( (TupleSinkNode) sink );
}
public void propagateAssertTuple(ReteTuple tuple,
InternalFactHandle handle,
TupleMatch tupleMatch,
PropagationContext context,
InternalWorkingMemory workingMemory) {
TupleSinkNode sink = this.sinks.getFirst();
ReteTuple joined = new ReteTuple(tuple, handle, (TupleSink) sink );
tupleMatch.addJoinedTuple( joined );
joined.assertTuple( context, workingMemory );
for ( sink = sink.getNextTupleSinkNode();sink != null; sink = sink.getNextTupleSinkNode() ) {
ReteTuple cloned = new ReteTuple(joined, sink);
tupleMatch.addJoinedTuple( cloned );
cloned.assertTuple( context, workingMemory );
}
}
public void propagateAssertTuple(ReteTuple tuple,
PropagationContext context,
InternalWorkingMemory workingMemory) {
for ( TupleSinkNode sink = this.sinks.getFirst(); sink != null; sink = sink.getNextTupleSinkNode() ) {
final ReteTuple child = new ReteTuple( tuple, sink );
// no TupleMatch so instead add as a linked tuple
tuple.addLinkedTuple( new LinkedListObjectWrapper( child ) );
child.assertTuple( context, workingMemory );
}
}
public void createAndAssertTuple(InternalFactHandle handle,
PropagationContext context,
InternalWorkingMemory workingMemory,
Map memory) {
final LinkedList list = new LinkedList();
memory.put( handle, list );
for ( TupleSinkNode sink = this.sinks.getFirst(); sink != null; sink = sink.getNextTupleSinkNode() ) {
ReteTuple tuple = new ReteTuple( handle, sink );
list.add( new LinkedListObjectWrapper( tuple ) );
tuple.assertTuple( context, workingMemory );
}
}
public TupleSink[] getSinks() {
TupleSink[] sinkArray = new TupleSink[ this.sinks.size() ];
int i =0;
for ( TupleSinkNode sink = this.sinks.getFirst(); sink != null; sink = sink.getNextTupleSinkNode() ) {
sinkArray[i++] = sink;
}
return sinkArray;
}
public void propagateNewTupleSink(TupleMatch tupleMatch,
PropagationContext context,
InternalWorkingMemory workingMemory) {
final TupleSink sink = sinks.getLast();
final ReteTuple tuple = new ReteTuple( tupleMatch.getTuple(),
tupleMatch.getObjectMatches().getFactHandle(),
sink );
tupleMatch.addJoinedTuple( tuple );
tuple.assertTuple( context, workingMemory );
}
public void propagateNewTupleSink(InternalFactHandle handle,
LinkedList list,
PropagationContext context,
InternalWorkingMemory workingMemory) {
TupleSink sink = this.sinks.getLast();
ReteTuple tuple = new ReteTuple( handle, sink );
list.add( new LinkedListObjectWrapper( tuple ) );
tuple.assertTuple( context, workingMemory );
}
/**
* @inheritDoc
*/
public List getPropagatedTuples(final Map memory,
final InternalWorkingMemory workingMemory,
final TupleSink sink) {
int index = 0;
for ( TupleSinkNode node = this.sinks.getFirst(); node != null; node = node.getNextTupleSinkNode() ) {
if ( node.equals( sink ) ) {
break;
}
index++;
}
final List propagatedTuples = new ArrayList( memory.size() );
for ( final Iterator it = memory.values().iterator(); it.hasNext(); ) {
final LinkedList tuples = (LinkedList) it.next();
LinkedListObjectWrapper wrapper = (LinkedListObjectWrapper) tuples.getFirst();
for ( int i = 0; i < index; i++ ) {
wrapper = (LinkedListObjectWrapper) wrapper.getNext();
}
propagatedTuples.add( wrapper.getObject() );
}
return propagatedTuples;
}
public int size() {
return this.sinks.size();
}
}
|
package edu.cmu.pocketsphinx;
import static java.lang.String.format;
import java.io.File;
import java.util.Collection;
import java.util.HashSet;
import android.media.AudioFormat;
import android.media.AudioRecord;
import android.media.MediaRecorder.AudioSource;
import android.os.*;
import android.util.Log;
import edu.cmu.pocketsphinx.Config;
import edu.cmu.pocketsphinx.Decoder;
import edu.cmu.pocketsphinx.Hypothesis;
public class SpeechRecognizer {
protected static final String TAG = SpeechRecognizer.class.getSimpleName();
private static final int MSG_START = 1;
private static final int MSG_STOP = 2;
private static final int MSG_CANCEL = 3;
private static final int BUFFER_SIZE = 1024;
private final Config config;
private final Decoder decoder;
private Thread recognizerThread;
private final Handler mainHandler = new Handler(Looper.getMainLooper());
private final Collection<RecognitionListener> listeners =
new HashSet<RecognitionListener>();
private final int sampleRate;
protected SpeechRecognizer(Config config) {
sampleRate = (int) config.getFloat("-samprate");
if (config.getFloat("-samprate") != sampleRate)
throw new IllegalArgumentException("sampling rate must be integer");
this.config = config;
decoder = new Decoder(config);
}
/**
* Adds listener.
*/
public void addListener(RecognitionListener listener) {
synchronized (listeners) {
listeners.add(listener);
}
}
/**
* Removes listener.
*/
public void removeListener(RecognitionListener listener) {
synchronized (listeners) {
listeners.remove(listener);
}
}
/**
* Starts recognition.
*
* @return true if recognition was actually started, false otherwise
*/
public boolean startListening(String searchName) {
if (null != recognizerThread)
return false;
Log.i(TAG, format("Start recognition \"%s\"", searchName));
decoder.setSearch(searchName);
recognizerThread = new RecognizerThread();
recognizerThread.start();
return true;
}
/**
* Stops recognition. All listeners should receive final result if there is
* any.
*/
public boolean stop() {
if (null == recognizerThread)
return false;
try {
recognizerThread.interrupt();
recognizerThread.join();
} catch (InterruptedException e) {
// Restore the interrupted status.
Thread.currentThread().interrupt();
}
recognizerThread = null;
return true;
}
/**
* Cancels recogition. Listeners do not recevie final result.
*/
public void cancel() {
// TODO: implement
}
/**
* Gets name of the currently active search.
*
* @return active search name or null if no search was started
*/
public String getSearchName() {
return decoder.getSearch();
}
public void addFsgSearch(String searchName, FsgModel fsgModel) {
decoder.setFsg(searchName, fsgModel);
}
/**
* Adds searches based on JSpeech grammar.
*
* @param name search name
* @param file JSGF file
*/
public void addGrammarSearch(String name, File file) {
Log.i(TAG, format("Load JSGF %s", file));
Jsgf jsgf = new Jsgf(file.getPath());
for (JsgfRule rule : jsgf) {
if (!rule.isPublic())
continue;
int lw = config.getInt("-lw");
Log.i(TAG, format("Use rule %s to build FSG", rule.getName()));
addFsgSearch(name, jsgf.buildFsg(rule, decoder.getLogmath(), lw));
return;
}
throw new IllegalArgumentException("grammar has no public rules");
}
/**
* Adds search based on N-gram language model.
*
* @param name search name
* @param file N-gram model file
*/
public void addNgramSearch(String name, File file) {
String path = file.getPath();
Log.i(TAG, format("Load N-gram model %s", path));
NGramModel lm = new NGramModel(config, decoder.getLogmath(), path);
decoder.setLm(name, lm);
}
/**
* Adds search based on a single phrase.
*
* @param name search name
* @param phrase search phrase
*/
public void addKeywordSearch(String name, String phrase) {
decoder.setKws(name, phrase);
}
private final class RecognizerThread extends Thread {
@Override public void run() {
AudioRecord recorder =
new AudioRecord(AudioSource.VOICE_RECOGNITION,
sampleRate,
AudioFormat.CHANNEL_IN_MONO,
AudioFormat.ENCODING_PCM_16BIT,
8192); // TODO:calculate properly
decoder.startUtt(null);
recorder.startRecording();
short[] buffer = new short[BUFFER_SIZE];
boolean vadState = decoder.getVadState();
while (!interrupted()) {
int nread = recorder.read(buffer, 0, buffer.length);
if (-1 == nread) {
throw new RuntimeException("error reading audio buffer");
} else if (nread > 0) {
decoder.processRaw(buffer, nread, false, false);
if (decoder.getVadState() != vadState) {
vadState = decoder.getVadState();
mainHandler.post(new VadStateChangeEvent(vadState));
}
final Hypothesis hypothesis = decoder.hyp();
if (null != hypothesis)
mainHandler.post(new ResultEvent(hypothesis, false));
}
}
recorder.stop();
int nread = recorder.read(buffer, 0, buffer.length);
recorder.release();
recorder = null;
decoder.processRaw(buffer, nread, false, false);
decoder.endUtt();
mainHandler.removeCallbacksAndMessages(null);
final Hypothesis hypothesis = decoder.hyp();
if (null != hypothesis)
mainHandler.post(new ResultEvent(hypothesis, true));
}
}
private abstract class RecognitionEvent implements Runnable {
public void run() {
RecognitionListener[] emptyArray = new RecognitionListener[0];
for (RecognitionListener listener : listeners.toArray(emptyArray))
execute(listener);
}
protected abstract void execute(RecognitionListener listener);
}
private class VadStateChangeEvent extends RecognitionEvent {
private final boolean state;
VadStateChangeEvent(boolean state) {
this.state = state;
}
@Override protected void execute(RecognitionListener listener) {
if (state)
listener.onBeginningOfSpeech();
else
listener.onEndOfSpeech();
}
}
private class ResultEvent extends RecognitionEvent {
protected final Hypothesis hypothesis;
private final boolean finalResult;
ResultEvent(Hypothesis hypothesis, boolean finalResult) {
this.hypothesis = hypothesis;
this.finalResult = finalResult;
}
@Override protected void execute(RecognitionListener listener) {
if (finalResult)
listener.onResult(hypothesis);
else
listener.onPartialResult(hypothesis);
}
}
}
/* vim: set ts=4 sw=4: */
|
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package edu.wpi.first.wpilibj.templates;
import edu.wpi.first.wpilibj.*;
/**
*
* @author RoboHawks
*/
public class drive {
Team3373 testing = new Team3373();
Joystick drivestick = new Joystick(1);
RobotDrive drive = new RobotDrive(1,2);
boolean XBOX_A = drivestick.getRawButton(1);
double XBOX_LSTICK = drivestick.getRawAxis(2);
public void Driving(){
if (XBOX_LSTICK >= -1 & XBOX_LSTICK <= 0 ){
}
}
}
|
package experimentalcode.hettab.outlier;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Random;
import java.util.TreeSet;
import java.util.Vector;
import de.lmu.ifi.dbs.elki.algorithm.AbstractAlgorithm;
import de.lmu.ifi.dbs.elki.data.DoubleVector;
import de.lmu.ifi.dbs.elki.database.Database;
import de.lmu.ifi.dbs.elki.result.MultiResult;
import de.lmu.ifi.dbs.elki.utilities.Description;
import de.lmu.ifi.dbs.elki.utilities.optionhandling.IntParameter;
import de.lmu.ifi.dbs.elki.utilities.optionhandling.OptionID;
import de.lmu.ifi.dbs.elki.utilities.optionhandling.ParameterException;
import de.lmu.ifi.dbs.elki.utilities.optionhandling.constraints.GreaterConstraint;
import de.lmu.ifi.dbs.elki.utilities.pairs.IntIntPair;
import de.lmu.ifi.dbs.elki.utilities.pairs.Pair;
import experimentalcode.hettab.AxisPoint;
import experimentalcode.hettab.MySubspace;
/**
* EAFOD provides the evolutionary outlier detection algorithm, an algorithm to detect
* outliers for high dimensional data
* <p>Reference:
* <br>Charu C. Aggarwal, Philip S. Yu :
* Outlier detection for high dimensional data
* <br>International Conference on Management of Data
* Proceedings of the 2001 ACM SIGMOD international conference on Management of data
* 2001 , Santa Barbara, California, United States
* </p>
* @author Ahmed Hettab
*
* @param <V> the type of FeatureVector handled by this Algorithm
*/
public class EAFOD<V extends DoubleVector> extends
AbstractAlgorithm<V, MultiResult> {
/**
* OptionID for {@link #M_PARAM}
*/
public static final OptionID M_ID = OptionID.getOrCreateOptionID("eafod.m",
"number of solutions");
/**
* Parameter to specify the number of solutions must be an integer greater
* than 1.
* <p>
* Key: {@code -eafod.m}
* </p>
*/
private final IntParameter M_PARAM = new IntParameter(M_ID,
new GreaterConstraint(0));
/**
* Holds the value of {@link #M_PARAM}.
*/
private int m;
/**
* OptionID for {@link #PHI_PARAM}
*/
public static final OptionID PHI_ID = OptionID.getOrCreateOptionID(
"eafod.phi", "the dimensoinality of projection");
/**
* Parameter to specify the equi-depth ranges must be an integer greater
* than 1.
* <p>
* Key: {@code -eafod.k}
* </p>
*/
private final IntParameter PHI_PARAM = new IntParameter(PHI_ID,
new GreaterConstraint(0));
/**
* Holds the value of {@link #PHI_PARAM}.
*/
private int phi;
/**
* OptionID for {@link #K_PARAM}
*/
public static final OptionID K_ID = OptionID.getOrCreateOptionID("eafod.k",
"the dimensoinality of projection");
/**
* Parameter to specify the dimensionality of projection must be an integer
* greater than 1.
* <p>
* Key: {@code -eafod.k}
* </p>
*/
private final IntParameter K_PARAM = new IntParameter(K_ID,
new GreaterConstraint(0));
/**
* Holds the value of {@link #K_PARAM}.
*/
private int k;
/**
* Holds the value of database dimensionality
*/
private int dim;
/**
* Holds the value of database size
*/
private int size;
/**
* Provides the result of the algorithm.
*/
MultiResult result;
/**
* Holds the value of equi-depth
*/
private HashMap<Integer, HashMap<Integer, HashSet<Integer>>> ranges;
/**
* random generator
*/
private Random random;
/**
* Provides the EAFOD algorithm,
* adding parameters
* {@link #M_PARAM}
* {@link #K_PARAM}
* {@link #PHI_PARAM}
* to the option handler additionally to parameters of super class.
*/
public EAFOD() {
addOption(K_PARAM);
addOption(M_PARAM);
addOption(PHI_PARAM);
ranges = new HashMap<Integer, HashMap<Integer, HashSet<Integer>>>();
random = new Random();
}
/**
* Performs the EAFOD algorithm on the given database.
*/
protected MultiResult runInTime(Database<V> database)
throws IllegalStateException {
double s=-Math.sqrt(database.size()/(Math.pow(phi,k)-1));
int k=(int)(Math.log(database.size()/(Math.pow(s, 2)+1))/Math.log(phi));
//this.k = k ;
System.out.println(k);
dim = database.dimensionality();
size = database.size();
// equiDempth sets
this.calculteDepth(database);
ArrayList<MySubspace> pop = this.initialPopulation(m);
// best Population
TreeSet<MySubspace> bestSol = new TreeSet<MySubspace>();
while (checkConvergence(bestSol) == false) {
System.out.println("selection");
pop = selection(pop);
System.out.println(pop);
// Crossover
System.out.println("crossover");
pop = crossover(pop);
System.out.println(pop);
// Mutation
System.out.println("mutation");
pop = mutation(pop, 0.5,0.5);
System.out.println(pop);
System.out.println();
bestSol.addAll(pop);
Iterator<MySubspace> tmp = bestSol.iterator();
TreeSet<MySubspace> tmp2 = new TreeSet<MySubspace>();
int i = 0;
while ((i < m) && (tmp.hasNext())) {
tmp2.add(tmp.next());
i++;
}
//update solution
bestSol = tmp2 ;
System.out.println("bestSol");
System.out.println(bestSol);
}
System.out.println("terminat");
System.out.println(bestSol);
List<Integer> outliers = new Vector<Integer>();
Iterator<MySubspace> mysubspace = bestSol.iterator() ;
while(mysubspace.hasNext()){
outliers.addAll(getIDs(mysubspace.next().getIndividual()));
}
//TODO
return null ;
}
/**
* grid discretization of the data :
* <br>each attribute of data is divided into phi equi-depth ranges .
* <br>each range contains a fraction f=1/phi of the records .
* @param database
*/
public void calculteDepth(Database<V> database) {
// sort dimension
ArrayList<ArrayList<AxisPoint>> dbAxis = new ArrayList<ArrayList<AxisPoint>>(
dim);
HashSet<Integer> range = new HashSet<Integer>();
HashMap<Integer, HashSet<Integer>> rangesAt = new HashMap<Integer, HashSet<Integer>>();
for (int i = 0; i < dim; i++) {
ArrayList<AxisPoint> axis = new ArrayList<AxisPoint>(size);
dbAxis.add(i, axis);
}
for (Integer id : database) {
for (int dim = 1; dim <= database.dimensionality(); dim++) {
double value = database.get(id).getValue(dim);
AxisPoint point = new AxisPoint(id, value);
dbAxis.get(dim - 1).add(point);
}
}
for (int index = 0; index < database.dimensionality(); index++) {
Collections.sort(dbAxis.get(index));
}
// equi-depth
// if range = 0 => |range| = database.size();
// if database.size()%phi == 0 |range|=database.size()/phi
// if database.size()%phi == rest (1..rest => |range| =
// database.size()/phi +1 , rest..phi => |range| = database.size()/phi
int rest = database.size() % phi;
int f = database.size() / phi;
HashSet<Integer> b = new HashSet<Integer>();
for (Integer id : database) {
b.add(id);
}
// if range = 0 => |range| = database.size();
for (int dim = 1; dim <= database.dimensionality(); dim++) {
rangesAt = new HashMap<Integer, HashSet<Integer>>();
rangesAt.put(0, b);
ranges.put(dim, rangesAt);
}
for (int dim = 1; dim <= database.dimensionality(); dim++) {
ArrayList<AxisPoint> axis = dbAxis.get(dim - 1);
for (int i = 0; i < rest; i++) {
// 1..rest => |range| = database.size()/phi +1
range = new HashSet<Integer>();
for (int j = i * f + i; j < (i + 1) * f + i + 1; j++) {
range.add(axis.get(j).getId());
}
ranges.get(dim).put(i + 1, range);
}
// rest..phi => |range| = database.size()/phi
for (int i = rest; i < phi; i++) {
range = new HashSet<Integer>();
for (int j = i * f + rest; j < (i + 1) * f + rest; j++) {
range.add(axis.get(j).getId());
}
ranges.get(dim).put(i + 1, range);
}
}
}
/**
* check the termination criterion
*
*/
public boolean checkConvergence(TreeSet<MySubspace> pop) {
if(pop.size()==0) return false ;
ArrayList<ArrayList<IntIntPair>> convDim = new ArrayList<ArrayList<IntIntPair>>();
boolean result = true;
MySubspace[] subspaces = new MySubspace[pop.size()];
subspaces = pop.toArray(subspaces);
// init count
for (int i = 0; i < pop.size(); i++) {
ArrayList<IntIntPair> tupels = new ArrayList<IntIntPair>();
for (int j = 0; j < dim; j++) {
tupels.add(j, new IntIntPair(j, 0));
}
convDim.add(i, tupels);
}
// calculate count
for (int i = 0; i < pop.size(); i++) {
for (int k = 0; k < dim; k++) {
int count = convDim.get(i).get(k).getSecond();
for (int j = 0; j < pop.size(); j++) {
if (subspaces[i].getIndividual()[k] == subspaces[j]
.getIndividual()[k]) {
count++;
}
convDim.get(i).get(k).setSecond(count);
}
}
}
for (int i = 0; i < convDim.size(); i++) {
boolean converged = false;
// convergence of each dimension
for (int j = 0; j < convDim.get(i).size(); j++) {
if (convDim.get(i).get(j).getSecond() >= pop.size() * 0.95)
converged = true;
}
if (!converged)
result = false;
}
return result;
}
/**
* Initial seed population
*/
public ArrayList<MySubspace> initialPopulation(int popsize) {
// Initial Population
ArrayList<MySubspace> population = new ArrayList<MySubspace>();
// fill population
for (int i = 0; i < popsize; i++) {
// Random Individual
int[] Individual = new int[dim];
// fill don't care ( any dimension == don't care)
for (int j = 0; j < dim; j++) {
Individual[j] = 0;
}
// count of don't care positions
int countDim = k;
// fill non don't care positions of the Individual
while (countDim > 0) {
int z = random.nextInt(dim);
if (Individual[z] == 0) {
Individual[z] = random.nextInt(phi) + 1;
countDim
}
}
population.add(new MySubspace(Individual, fitness(Individual)));
}
Collections.sort(population);
return population;
}
/**
* the selection criterion for the genetic algorithm:
* <br>
* roulette wheel machanism:
* <br>
* where the probability of sampling an individual of the population
* was proportional to p - r(i), where p is the size of population and r(i) the rank of i-th individual
* @param population
*/
public ArrayList<MySubspace> selection(ArrayList<MySubspace> population) {
// probability
// Roulette weehl
Vector<Integer> probability = new Vector<Integer>();
// set of selected individual
ArrayList<MySubspace> newPopulation = new ArrayList<MySubspace>();
int sum = 0;
probability.add(sum);
// calculate probability
for (int t = 0; t < population.size(); t++) {
sum = sum + (population.size() - t);
probability.add(sum);
}
// position of selection
for (int i = 0; i < population.size(); i++) {
int z = random.nextInt(sum);
for (int j = 0; j < probability.size() - 1; j++) {
if (z >= probability.get(j) && z <= probability.get(j + 1)) {
// add selected pop
MySubspace subspace = population.get(j);
newPopulation.add(subspace);
}
}
}
if (newPopulation.size() == 0) {
System.exit(0);
}
//sort initialPopulation
Collections.sort(newPopulation);
return newPopulation;
}
/**
* method implements the mutation algorithm
*/
public ArrayList<MySubspace> mutation(ArrayList<MySubspace> population,
double perc1, double perc2) {
// the Mutations
ArrayList<MySubspace> mutations = new ArrayList<MySubspace>();
// Set of Positions which are dont care in the String
TreeSet<Integer> Q = new TreeSet<Integer>();
// Set of Positions which are not dont care in the String
TreeSet<Integer> R = new TreeSet<Integer>();
// for each Individuum
for (int j = 0; j < population.size(); j++) {
// clear the Sets
Q.clear();
R.clear();
// Fill the Sets with the Positions
for (int i = 0; i < dim; i++) {
if (population.get(j).getIndividual()[i] == 0) {
Q.add(i);
} else {
R.add(i);
}
}
double r1 = random.nextDouble() ;
if (Q.size() != 0){
// Mutation Variant 1
if (r1 <= perc1) {
// calc Mutation Spot
Integer[] pos = new Integer[Q.size()];
pos = Q.toArray(pos);
int position = random.nextInt(pos.length);
int depth = pos[position];
// Mutate dont Care into 1....phi
population.get(j).getIndividual()[depth] = random
.nextInt(phi) + 1;
// update Sets
Q.remove(depth);
R.add(depth);
// calc new Mutation Spot
pos = new Integer[R.size()];
pos = R.toArray(pos);
position = random.nextInt(pos.length);
depth = pos[position];
// Mutate non dont care into dont care
population.get(j).getIndividual()[depth] = 0;
// update Sets
Q.add(depth);
R.remove(depth);
}
}
r1 = random.nextDouble() ;
// Mutation Variant 2
if (r1 <= perc2) {
// calc Mutation Spot
Integer[] pos = new Integer[R.size()];
pos = R.toArray(pos);
int position = random.nextInt(pos.length);
int depth = pos[position];
// Mutate 1...phi into another 1...phi
population.get(j).getIndividual()[depth] = random
.nextInt(phi) + 1;
}
int[] individual = population.get(j).getIndividual();
mutations.add(new MySubspace(individual, fitness(individual)));
}
Collections.sort(mutations);
return mutations;
}
/**
* method calculate the fitness of individual
* @param individual
* @return sparsity coefficient
*/
public double fitness(int[] individual) {
HashSet<Integer> m = new HashSet<Integer>(ranges.get(1).get(
individual[0]));
//intersect
for (int i = 2; i <= individual.length; i++) {
HashSet<Integer> current = new HashSet<Integer>(ranges.get(i).get(
individual[i - 1]));
HashSet<Integer> result = retainAll(m, current);
m.clear();
m.addAll(result);
}
//calculate sparsity c
double f = (double) 1 / phi;
double nD = (double) m.size();
double fK = Math.pow(f, k);
double sC = (nD - (size * fK)) / Math.sqrt(size * fK * (1 - fK));
return sC;
}
/**
* method get the ids of individual
*/
public Vector<Integer> getIDs (int[] individual){
HashSet<Integer> m = new HashSet<Integer>(ranges.get(1).get(
individual[0]));
//intersect
for (int i = 2; i <= individual.length; i++) {
HashSet<Integer> current = new HashSet<Integer>(ranges.get(i).get(
individual[i - 1]));
HashSet<Integer> result = retainAll(m, current);
m.clear();
m.addAll(result);
}
Vector<Integer> ids = new Vector<Integer>();
ids.addAll(m);
return ids ;
}
/**
* method implements the crossover algorithm
*
*/
public ArrayList<MySubspace> crossover(ArrayList<MySubspace> population) {
// Crossover Set of population Set
ArrayList<MySubspace> crossover = new ArrayList<MySubspace>();
// recombine vector
Pair<MySubspace , MySubspace> recombine ;
MySubspace[] pop = new MySubspace[population.size()];
pop = population.toArray(pop);
int i = 0;
// Match the Solutions pairwise
while (i < (population.size() / 2) * 2) {
recombine = recombine(pop[i], pop[i + 1]);
i = i + 2;
// add the Solutions to the new Set
crossover.add(recombine.getFirst());
crossover.add(recombine.getSecond());
}
// if the set contains an odd number of Subspaces
if (pop.length % 2 == 1)
crossover.add(pop[pop.length - 1]);
Collections.sort(crossover);
return crossover;
}
/**
*
* method implements the recombine algorithm
*/
public Pair<MySubspace,MySubspace> recombine(MySubspace s1, MySubspace s2) {
Pair<MySubspace,MySubspace> recombinePair ;
// Set of Positions in which either s1 or s2 are dont care
TreeSet<Integer> Q = new TreeSet<Integer>();
// Set of Positions in which neither s1 or s2 is dont care
TreeSet<Integer> R = new TreeSet<Integer>();
for (int i = 0; i < s1.getIndividual().length; i++) {
if ((s1.getIndividual()[i] == 0) && (s2.getIndividual()[i] != 0))
Q.add(i);
if ((s2.getIndividual()[i] == 0) && (s1.getIndividual()[i] != 0))
Q.add(i);
if ((s1.getIndividual()[i] != 0) && (s2.getIndividual()[i] != 0)) {
R.add(i);
}
}
int[] best2R = new int[dim];
//select the fittest combination of R
if(R.size()!=0){
TreeSet<MySubspace> bestCombi = new TreeSet<MySubspace>();
//best 2R Combination
ArrayList<int[]> best = comb(R, s1, s2);
Iterator<int[]> m = best.iterator();
while (m.hasNext()) {
int[] next = m.next();
bestCombi.add(new MySubspace(next, fitness(next)));
}
best2R = bestCombi.first().getIndividual();
}
//if R.size() == 0 only extends String
else{
for(int i = 0 ;i<dim ; i++){
best2R[i]= 0 ;
}
}
//Extends String greedily
int[] b = best2R.clone();
int count = k - R.size();
Iterator<Integer> q = Q.iterator();
while (count > 0) {
int pos = 0 ;
int[] l1 = b.clone();
int[] l2 = b.clone();
while (q.hasNext()) {
int next = q.next();
pos = next ;
{
boolean s1Null = (s1.getIndividual()[next] == 0);
boolean s2Null = (s1.getIndividual()[next] == 0);
l1[next] = s1.getIndividual()[next];
l2[next] = s2.getIndividual()[next];
if (fitness(l1) >= fitness(l2)) {
b = l1.clone();
if (s1Null) count
}
else {
b = l2.clone();
if (s2Null) count
}
}
}
Q.remove(pos);
}
best2R = b.clone();
// create the complementary String
int[] comp = new int[dim];
for (int i = 0; i < dim; i++) {
if (best2R[i] == s1.getIndividual()[i])
comp[i] = s2.getIndividual()[i];
else
comp[i] = s2.getIndividual()[i];
}
recombinePair = new Pair<MySubspace , MySubspace>(new MySubspace(best2R, fitness(best2R)),new MySubspace(comp, fitness(comp)));
return recombinePair;
}
/**
* method
*/
public static MySubspace nullSubspace(int dim) {
int[] individual = new int[dim];
for (int i = 0; i < dim; i++) {
individual[i] = 0;
}
return new MySubspace(individual);
}
/**
*
* @param set1
* @param set2
* @return
*/
public static HashSet<Integer> retainAll(HashSet<Integer> set1,
HashSet<Integer> set2) {
HashSet<Integer> result = new HashSet<Integer>();
for (Integer id : set1) {
if (set2.contains(id)) {
result.add(id);
}
}
for (Integer id : set2) {
if (set1.contains(id)) {
result.add(id);
}
}
return result;
}
/**
* method
*/
public static ArrayList<int[]> comb(TreeSet<Integer> R, MySubspace s1,
MySubspace s2) {
ArrayList<int[]> mySubspaces = new ArrayList<int[]>();
int size = R.size();
HashMap<Integer, ArrayList<String>> comb = new HashMap<Integer, ArrayList<String>>();
ArrayList<String> r1 = new ArrayList<String>();
r1.add(new String("1"));
r1.add(new String("2"));
comb.put(1, r1);
for (int i = 2; i <= size; i++) {
ArrayList<String> ri = new ArrayList<String>();
ArrayList<String> rOld = comb.get(i - 1);
for (int j = 0; j < rOld.size(); j++) {
String neu1 = rOld.get(j) + "1";
String neu2 = rOld.get(j) + "2";
ri.add(neu1);
ri.add(neu2);
}
comb.put(i, ri);
comb.remove(i - 1);
}
for (int i = 0; i < comb.get(size).size(); i++) {
Iterator<Integer> r = R.iterator();
MySubspace m = nullSubspace(s1.getIndividual().length);
String s = comb.get(size).get(i);
for (int pos = 0; pos < s.length(); pos++) {
int d = r.next();
if (s.charAt(pos) == '1') {
m.getIndividual()[d] = s1.getIndividual()[d];
}
if (s.charAt(pos) == '2') {
m.getIndividual()[d] = s2.getIndividual()[d];
}
}
int[] t = m.getIndividual().clone();
mySubspaces.add(t);
}
return mySubspaces;
}
@Override
public Description getDescription() {
return new Description("shortTitle", "longTitle", "purposeAndDescription", "reference");
}
@Override
public MultiResult getResult() {
// TODO Auto-generated method stub
return null;
}
/**
* Calls the super method and additionally sets the values of the parameters
* {@link #K_PARAM} and {@link #M_PARAM} and {@link #PHI_PARAM}
*/
@Override
public List<String> setParameters(List<String> args)
throws ParameterException {
List<String> remainingParameters = super.setParameters(args);
k = K_PARAM.getValue();
m = M_PARAM.getValue();
phi = PHI_PARAM.getValue();
return remainingParameters;
}
}
|
package galileo.test.through;
import java.io.IOException;
import galileo.event.ConcurrentEventReactor;
import galileo.event.EventContext;
import galileo.event.EventHandler;
import galileo.net.ServerMessageRouter;
public class ThroughputServer {
protected static final int PORT = 5050;
protected static final int QUERY_SIZE = 64;
protected static final int REPLY_SIZE = 4096;
private ThroughputEventMap eventMap = new ThroughputEventMap();
private ConcurrentEventReactor reactor
= new ConcurrentEventReactor(this, eventMap, 8);
private ServerMessageRouter messageRouter;
public void start()
throws IOException {
messageRouter = new ServerMessageRouter();
messageRouter.addListener(reactor);
messageRouter.listen(PORT);
System.out.println("Listening on port " + PORT);
}
@EventHandler
public void handleMessage(ThroughputMessage msg, EventContext context) {
byte[] payload = msg.getPayload();
System.out.println("Got " + payload.length + " bytes from "
+ context.getSource());
}
public static void main(String[] args) throws Exception {
ThroughputServer serv = new ThroughputServer();
serv.start();
}
}
|
package gov.nih.nci.rembrandt.util;
import java.util.HashMap;
import org.apache.log4j.Logger;
/**
* @author BhattarR
*/
public class ThreadPool {
static HashMap allThreads = new HashMap();
public final static long MAX_THREADS = 400;
public static long THREAD_COUNT = 0;
private static Logger logger = Logger.getLogger(ThreadPool.class);
public synchronized static AppThread newAppThread(MyRunnable r) {
while (THREAD_COUNT >= MAX_THREADS ) {
try {
Thread.currentThread().sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
AppThread appThread = new AppThread(r);
logger.debug("BEGIN: New thread created. Thread Count: " + ThreadPool.THREAD_COUNT);
return appThread;
}
public static class AppThread {
private MyRunnable ar = null;
Thread t = null;
Long ID;
public void execute() {
ar.codeToRun();
synchronized(allThreads) {
THREAD_COUNT
allThreads.remove(this.getID());
};
logger.debug("END: Thread completed. Thread Count: " + ThreadPool.THREAD_COUNT);
}
private AppThread(MyRunnable appRunnable) {
this.ar = appRunnable;
t= new Thread(new Runnable() {
public void run() {
execute();
}
});
synchronized(allThreads) {
THREAD_COUNT++;
ID = new Long(System.currentTimeMillis() + THREAD_COUNT);
allThreads.put(this.getID(), this);
};
}
public Long getID(){
return ID;
}
public void start() {
t.start();
}
}
public static interface MyRunnable {
public void codeToRun();
}
}
|
package scrum.client.test;
import com.allen_sauer.gwt.dnd.client.DragContext;
import com.allen_sauer.gwt.dnd.client.PickupDragController;
import com.allen_sauer.gwt.dnd.client.drop.SimpleDropController;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.MouseListener;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.gwt.user.client.ui.SourcesMouseEvents;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.google.gwt.user.client.ui.Widget;
public class TestWidget extends Composite {
private PickupDragController dragController = new PickupDragController(RootPanel.get(), false);
public TestWidget() {
VerticalPanel panel = new VerticalPanel();
panel.setStyleName("TestWidget");
panel.setSpacing(30);
DragWidget drag = new DragWidget();
DropWidget drop = new DropWidget();
dragController.makeDraggable(drag);
TestDropController dropController = new TestDropController(drop);
dragController.registerDropController(dropController);
panel.add(drag);
panel.add(drop);
initWidget(panel);
}
class DragWidget extends Composite implements SourcesMouseEvents {
Label label = new Label("dragMe");
public DragWidget() {
initWidget(label);
}
public void addMouseListener(MouseListener listener) {
label.addMouseListener(listener);
}
public void removeMouseListener(MouseListener listener) {
label.removeMouseListener(listener);
}
}
class DropWidget extends Composite {
int dropped = 0;
Label label = new Label("Drop here! (dropped 0)");
public DropWidget() {
initWidget(label);
}
public void increment() {
label.setText("Drop here! (dropped " + (++dropped) + ")");
}
}
public class TestDropController extends SimpleDropController {
private DropWidget widget;
public TestDropController(Widget dropTarget) {
super(dropTarget);
widget = (DropWidget) dropTarget;
}
@Override
public void onDrop(DragContext context) {
super.onDrop(context);
widget.increment();
}
@Override
public void onEnter(DragContext context) {
super.onEnter(context);
}
@Override
public void onLeave(DragContext context) {
super.onLeave(context);
}
}
}
|
package info.ata4.unity.cli.utils;
import info.ata4.unity.asset.AssetFile;
import info.ata4.unity.asset.struct.AssetFieldType;
import info.ata4.unity.asset.struct.AssetObjectPath;
import info.ata4.unity.asset.struct.AssetTypeTree;
import info.ata4.unity.cli.DisUnitySettings;
import info.ata4.unity.serdes.Deserializer;
import info.ata4.unity.serdes.UnityBuffer;
import info.ata4.unity.serdes.UnityField;
import info.ata4.unity.serdes.UnityList;
import info.ata4.unity.serdes.UnityObject;
import info.ata4.unity.util.ClassID;
import java.io.PrintStream;
import java.nio.ByteBuffer;
import java.util.List;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.xml.bind.DatatypeConverter;
/**
*
* @author Nico Bergemann <barracuda415 at yahoo.de>
*/
public class AssetDumper {
private static final Logger L = Logger.getLogger(AssetDumper.class.getName());
private static final String INDENT_STRING = " ";
private final AssetFile asset;
private final DisUnitySettings settings;
private PrintStream ps;
private int indentLevel;
public AssetDumper(AssetFile asset, DisUnitySettings settings) {
this.asset = asset;
this.settings = settings;
}
public void dumpData(PrintStream ps) {
this.ps = ps;
Deserializer deser = new Deserializer(asset);
for (AssetObjectPath path : asset.getObjectPaths()) {
try {
if (path.classID2 < 0) {
continue;
}
// skip filtered classes
if (settings.isClassFiltered(path.classID2)) {
continue;
}
printObject(deser.deserialize(path));
} catch (Exception ex) {
L.log(Level.SEVERE, "Deserialization failed for " + path.pathID + " (" + ClassID.getInstance().getNameForID(path.classID2) + ")", ex);
break;
}
}
}
public void dumpStruct(PrintStream ps) {
this.ps = ps;
AssetTypeTree typeTree = asset.getTypeTree();
if (typeTree.isStandalone()) {
L.info("No type tree available");
return;
}
Set<Integer> classIDs = asset.getClassIDs();
for (Integer classID : classIDs) {
// skip filtered classes
if (settings.isClassFiltered(classID)) {
continue;
}
AssetFieldType classField = typeTree.get(classID);
if (classField == null) {
continue;
}
printType(classField);
}
}
private void printObject(UnityObject obj) {
ps.print(obj.getType());
if (!obj.getName().equals("Base")) {
ps.print(" ");
ps.println(obj.getName());
} else {
ps.println();
}
indentLevel++;
for (UnityField field : obj.getFields()) {
printIndent();
Object value = field.getValue();
if (value instanceof UnityObject) {
printObject((UnityObject) value);
} else {
printField(field);
}
}
indentLevel
}
private void printField(UnityField field) {
String name = field.getName();
String type = field.getType();
Object value = field.getValue();
if (name.contains(" ")) {
ps.printf("%s \"%s\" = ", type, name, value);
} else {
ps.printf("%s %s = ", type, name, value);
}
indentLevel++;
printValue(value);
indentLevel
}
private void printValue(Object value) {
if (value instanceof UnityObject) {
printObject((UnityObject) value);
} else if (value instanceof UnityList) {
UnityList array = (UnityList) value;
List<Object> list = array.getList();
ps.printf("%s[%d]\n", array.getType(), list.size());
for (Object value2 : list) {
printIndent();
printValue(value2);
}
} else if (value instanceof UnityBuffer) {
ByteBuffer bb = ((UnityBuffer) value).getBuffer();
ps.printf("byte[%d]\n", bb.capacity());
printBytes(bb);
} else if (value instanceof String) {
ps.printf("\"%s\"\n", value);
} else {
ps.println(value);
}
}
private void printType(AssetFieldType field) {
String name = field.name;
String type = field.type;
printIndent();
ps.print(type);
if (!name.equals("Base")) {
ps.print(" ");
ps.println(name);
} else {
ps.println();
}
indentLevel++;
for (AssetFieldType subField : field) {
printType(subField);
}
indentLevel
}
private void printBytes(ByteBuffer bb) {
byte[] block = new byte[256];
ByteBuffer bb2 = bb.duplicate();
bb2.rewind();
while (bb2.hasRemaining()) {
int len = Math.min(bb2.remaining(), block.length);
bb2.get(block, 0, len);
printIndent();
ps.println(DatatypeConverter.printHexBinary(block));
}
}
private void printIndent() {
for (int i = 0; i < indentLevel; i++) {
ps.print(INDENT_STRING);
}
}
}
|
// Clirr: compares two versions of a java library for binary compatibility
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// This library is distributed in the hope that it will be useful,
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// You should have received a copy of the GNU Lesser General Public
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
package net.sf.clirr.event;
import org.apache.bcel.classfile.JavaClass;
import org.apache.bcel.classfile.AccessFlags;
import org.apache.bcel.classfile.Attribute;
import org.apache.bcel.classfile.InnerClasses;
import org.apache.bcel.classfile.InnerClass;
import org.apache.bcel.classfile.ConstantPool;
import org.apache.bcel.classfile.Constant;
import org.apache.bcel.classfile.ConstantUtf8;
import org.apache.bcel.util.Repository;
import org.apache.bcel.Constants;
import net.sf.clirr.framework.CheckerException;
/**
* Selects zero or more java scope values (public, protected, package,
* private). An instance of this class is used when comparing two versions
* of an application to indicate what items are of interest. When the target
* audience is "normal" users of the applications, only changes to items
* which have public or protected scope are relevant. When the audience is
* developers of the applications, then package-scope and private-scope
* changes are also of interest.
*
* @author Simon Kitching
*/
public final class ScopeSelector
{
/**
* Represents an "accessability" level for a java class, field or method.
* <p>
* Change of access rights from lower to higher visibility rating is a
* binary-compatible change. Change of access rights from higher to
* lower is a binary-incompatible change.
* <p>
* Public > Protected > Package > Private
*/
public static final class Scope
{
private int vis;
private String desc;
private String decl;
private Scope(int vis, String desc, String decl)
{
this.vis = vis;
this.desc = desc;
this.decl = decl;
}
public boolean isMoreVisibleThan(Scope v)
{
return this.vis > v.vis;
}
public boolean isLessVisibleThan(Scope v)
{
return this.vis < v.vis;
}
public String getDesc()
{
return desc;
}
public String getDecl()
{
return decl;
}
}
/** Object representing private scoped objects. */
public static final Scope SCOPE_PRIVATE = new Scope(0, "private", "private");
/** Object representing package scoped objects. */
public static final Scope SCOPE_PACKAGE = new Scope(1, "package", "");
/** Object representing protected scoped objects. */
public static final Scope SCOPE_PROTECTED = new Scope(2, "protected", "protected");
/** Object representing public scoped objects. */
public static final Scope SCOPE_PUBLIC = new Scope(3, "public", "public");
private Scope scope = SCOPE_PROTECTED;
/**
* Construct an instance which selects public and protected objects and
* ignores package and private objects. The selectXXX methods can later
* be used to adjust this default behaviour.
*/
public ScopeSelector()
{
}
/**
* Construct an instance which selects public and protected objects and
* ignores package and private objects. The selectXXX methods can later
* be used to adjust this default behaviour.
*/
public ScopeSelector(Scope scope)
{
this.scope = scope;
}
/** Specify which scope objects are of interest. */
public void setScope(Scope scope)
{
this.scope = scope;
}
/**
* Get the scope that this object is configured with.
*/
public Scope getScope()
{
return scope;
}
/**
* Return a string which indicates what scopes this object will consider
* to be selected (ie relevant).
*/
public String toString()
{
return scope.getDesc();
}
/**
* Given a BCEL object, return true if this object's scope is one of the
* values this object is configured to match.
* <p>
* Note that BCEL classes Field and Method inherit from the AccessFlags
* base class and so are valid parameters to this method.
* <p>
* Note that despite JavaClass objects extending AccessFlags, the
* methods which determine the accessability of a JavaClass fail
* miserably (bad bcel design) for nested classes. Therefore this
* method <i>must not</i> be passed a JavaClass object as a parameter.
* If this is done, a RuntimeException will be thrown to indicate a
* programmer error.
*
* @param object is the object whose scope is to be checked.
* @return true if the object is selected.
*/
public boolean isSelected(AccessFlags object)
{
return !getScope(object).isLessVisibleThan(scope);
}
/**
* Return true if objects of the specified scope, or more visible,
* are selected by this selector.
*
* @param scope is the scope being checked
* @return true if objects of the specified scope are selected.
*/
public boolean isSelected(Scope scope)
{
return !scope.isLessVisibleThan(this.scope);
}
/**
* Given a BCEL object, return the string which would be used in java
* source code to declare that object's scope. <p>
* <p>
* Note that BCEL classes Field and Method inherit from the AccessFlags
* base class and so are valid parameters to this method.
* <p>
* Note that despite JavaClass objects extending AccessFlags, the
* methods which determine the accessability of a JavaClass fail
* miserably (bad bcel design) for nested classes. Therefore this
* method <i>must not</i> be passed a JavaClass object as a parameter.
* If this is done, a RuntimeException will be thrown to indicate a
* programmer error.
*/
public static String getScopeDecl(AccessFlags object)
{
return getScope(object).getDecl();
}
/**
* Given an integer representing an object's access flags, return the
* string which would be used in java source code to declare that object's
* scope.
* <p>
* Note that this method gives the wrong results for JavaClass objects
* which are nested classes. Use getClassScope(jclass).getDecl() instead.
*/
public static String getScopeDecl(int accessFlags)
{
return getScope(accessFlags).getDecl();
}
/**
* Given a BCEL object, return a string indicating whether the object is
* public/protected/private/package scope. This is similar to
* getScopeName, except for package-scope objects where this method
* returns the string "package".
* <p>
* Note that BCEL classes Field and Method inherit from the AccessFlags
* base class and so are valid parameters to this method.
* <p>
* Note that despite JavaClass objects extending AccessFlags, the
* methods which determine the accessability of a JavaClass fail
* miserably (bad bcel design) for nested classes. Therefore this
* method <i>must not</i> be passed a JavaClass object as a parameter.
* If this is done, a RuntimeException will be thrown to indicate a
* programmer error.
*/
public static String getScopeDesc(AccessFlags object)
{
return getScope(object).getDesc();
}
/**
* Given an integer representing the object's access flags, return a string
* indicating whether the object is public/protected/private/package scope.
* <p>
* This is similar to getScopeName, except for package-scope objects where
* this method returns the string "package".
* <p>
* Note that this method gives the wrong results for JavaClass objects
* which are nested classes. Use getClassScope(jclass).getDesc() instead.
*/
public static String getScopeDesc(int accessFlags)
{
return getScope(accessFlags).getDesc();
}
/**
* Get a Scope object representing the accessibility of the specified
* object.
* <p>
* Note that BCEL classes Field and Method inherit from the AccessFlags
* base class and so are valid parameters to this method.
* <p>
* Note that despite JavaClass objects extending AccessFlags, the
* methods which determine the accessability of a JavaClass fail
* miserably (bad bcel design) for nested classes. Therefore this
* method <i>must not</i> be passed a JavaClass object as a parameter.
* If this is done, a RuntimeException will be thrown to indicate a
* programmer error. Use getClassScope instead.
*/
public static Scope getScope(AccessFlags object)
{
if (object instanceof JavaClass)
{
throw new RuntimeException(
"getScope called for JavaClass object. This is not permitted;"
+ " use method getClassScope for JavaClass objects.");
}
return getScope(object.getAccessFlags());
}
/**
* Get a Scope object representing the accessibility of the specified
* object.
* <p>
* Note that this method gives the wrong results for JavaClass objects
* which are nested classes. Use getClassScope(jclass) instead.
*/
public static Scope getScope(int accessFlags)
{
if ((accessFlags & Constants.ACC_PUBLIC) > 0)
{
return SCOPE_PUBLIC;
}
if ((accessFlags & Constants.ACC_PROTECTED) > 0)
{
return SCOPE_PROTECTED;
}
if ((accessFlags & Constants.ACC_PRIVATE) > 0)
{
return SCOPE_PRIVATE;
}
return SCOPE_PACKAGE;
}
/**
* Java class files only ever contain scope specifiers of "public" or
* "package". For top-level classes, this is expected: it is not possible
* to have a top-level protected or private class.
* <p>
* However nested classes <i>can</i> be declared as protected or private. The
* way to tell the real scope of a nested class is to ignore the scope in
* the actual class file itself, and instead look in the "InnerClasses"
* attribute stored on the enclosing class. This is exactly what the java
* compiler does when compiling, and what the jvm does when verifying class
* linkage at runtime.
* <p>
* For a "top-level" class, this method just returns the access scope for
* the class itself. For nested classes, the enclosing class of the
* specified class is retrieved and its InnerClasses attribute checked to
* find the true scope for the specified class.
* <p>
* @throws CheckerException if the specified class is a nested class and
* the enclosing class could not be found, or if the supposedly enclosing
* class has no reference to the nested class. This exception is not
* expected to occur in practice, unless a truly screwed-up jar file is
* passed to clirr for inspection.
*/
public static Scope getClassScope(JavaClass jclass) throws CheckerException
{
int dollarPos = jclass.getClassName().lastIndexOf('$');
if (dollarPos == -1)
{
// not a nested class
return getScope(jclass.getAccessFlags());
}
// ok this is a nested class
String jclassName = jclass.getClassName();
String enclosingClassName = jclassName.substring(0, dollarPos);
String jclassNestedName = jclassName.substring(dollarPos + 1);
Repository repo = jclass.getRepository();
JavaClass enclosingClass = repo.findClass(enclosingClassName);
if (enclosingClass == null)
{
throw new CheckerException(
"Unable to locate enclosing class " + enclosingClassName
+ " for nested class " + jclassName);
}
ConstantPool pool = enclosingClass.getConstantPool();
Attribute[] attrs = enclosingClass.getAttributes();
for (int i = 0; i < attrs.length; ++i)
{
if (attrs[i] instanceof InnerClasses)
{
InnerClasses ics = (InnerClasses) attrs[i];
InnerClass[] icarray = ics.getInnerClasses();
for (int j = 0; j < icarray.length; ++j)
{
InnerClass ic = icarray[j];
int nameIndex = ic.getInnerNameIndex();
Constant nameconst = pool.getConstant(nameIndex);
if (nameconst instanceof ConstantUtf8)
{
String classname = ((ConstantUtf8) nameconst).getBytes();
if (jclassNestedName.equals(classname))
{
return getScope(ic.getInnerAccessFlags());
}
}
}
}
}
// weird; no nested class info found
throw new CheckerException(
"Unable to find information in class " + enclosingClass.getClassName()
+ " referring back to nested class " + jclassName);
}
}
|
package org.concord.otrunk.view;
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.FileDialog;
import java.awt.Frame;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.File;
import java.net.URL;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.Vector;
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.JCheckBoxMenuItem;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JRootPane;
import javax.swing.JScrollPane;
import javax.swing.JSplitPane;
import javax.swing.JTabbedPane;
import javax.swing.JTextArea;
import javax.swing.JTree;
import javax.swing.SwingUtilities;
import javax.swing.WindowConstants;
import javax.swing.event.TreeSelectionEvent;
import javax.swing.event.TreeSelectionListener;
import org.concord.framework.otrunk.OTID;
import org.concord.framework.otrunk.OTObject;
import org.concord.framework.otrunk.OTObjectMap;
import org.concord.framework.otrunk.OTrunk;
import org.concord.framework.otrunk.view.OTFrame;
import org.concord.framework.otrunk.view.OTViewContainer;
import org.concord.framework.otrunk.view.OTViewContainerListener;
import org.concord.framework.util.SimpleTreeNode;
import org.concord.otrunk.OTStateRoot;
import org.concord.otrunk.OTUserListService;
import org.concord.otrunk.OTrunkImpl;
import org.concord.otrunk.datamodel.OTDataObject;
import org.concord.otrunk.user.OTReferenceMap;
import org.concord.otrunk.user.OTUserObject;
import org.concord.otrunk.xml.Exporter;
import org.concord.otrunk.xml.XMLDatabase;
import org.concord.swing.util.Util;
import org.concord.view.SimpleTreeModel;
import org.concord.view.SwingUserMessageHandler;
/**
* OTViewer
* Class name and description
*
* Date created: Dec 14, 2004
*
* @author scott<p>
*
*/
public class OTViewer extends JFrame
implements TreeSelectionListener, OTFrameManager,
OTViewContainerListener
{
public final static int NO_USER_MODE = 0;
public final static int SINGLE_USER_MODE = 1;
public final static int MULTIPLE_USER_MODE = 2;
private static OTrunkImpl otrunk;
private static OTViewFactory otViewFactory;
protected int userMode = 0;
/**
* users in the otml file
*/
private HashMap users = new HashMap();
private URL usersURL = null;
OTUserObject currentUser = null;
URL currentURL = null;
OTViewContainerPanel bodyPanel;
JTree folderTreeArea;
SimpleTreeModel folderTreeModel;
JTree dataTreeArea;
SimpleTreeModel dataTreeModel;
JSplitPane splitPane;
//Temp, to close the window
AbstractAction exitAction;
AbstractAction saveAsAction;
JMenuBar menuBar;
XMLDatabase xmlDB;
XMLDatabase userDataDB;
File currentAuthoredFile = null;
File currentUserFile = null;
Hashtable otContainers = new Hashtable();
String startupMessage = "";
boolean showTree = false;
private AbstractAction saveUserDataAsAction;
private AbstractAction saveUserDataAction;
private AbstractAction debugAction;
private AbstractAction newUserDataAction;
private AbstractAction loadUserDataAction;
private AbstractAction loadAction;
private AbstractAction saveAction;
private AbstractAction exportImageAction;
private AbstractAction exportHiResImageAction;
public static void setOTViewFactory(OTViewFactory factory)
{
otViewFactory = factory;
}
public OTViewer(boolean showTree)
{
super("OTrunk Viewer");
this.showTree = showTree;
setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE);
addWindowListener( new WindowAdapter() {
public void windowClosing(WindowEvent e)
{
((OTViewer)e.getSource()).exit();
}
});
}
public void setUserMode(int mode)
{
userMode = mode;
}
public void updateTreePane()
{
Dimension minimumSize = new Dimension(100, 50);
JComponent leftComponent = null;
folderTreeArea = new JTree(folderTreeModel);
folderTreeArea.setEditable(true);
folderTreeArea.addTreeSelectionListener(this);
JScrollPane folderTreeScrollPane = new JScrollPane(folderTreeArea);
if(System.getProperty("otrunk.view.debug","").equals("true")){
// ViewFactory.getComponent(root);
dataTreeArea = new JTree(dataTreeModel);
dataTreeArea.setEditable(true);
dataTreeArea.addTreeSelectionListener(this);
JScrollPane dataTreeScrollPane = new JScrollPane(dataTreeArea);
JTabbedPane tabbedPane = new JTabbedPane();
tabbedPane.add("Folders", folderTreeScrollPane);
tabbedPane.add("Resources", dataTreeScrollPane);
// Provide minimum sizes for the two components in the split pane
folderTreeScrollPane.setMinimumSize(minimumSize);
dataTreeScrollPane.setMinimumSize(minimumSize);
tabbedPane.setMinimumSize(minimumSize);
leftComponent = tabbedPane;
} else {
leftComponent = folderTreeScrollPane;
}
if(splitPane == null){
splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT,
leftComponent, bodyPanel);
} else {
splitPane.setLeftComponent(leftComponent);
}
splitPane.setOneTouchExpandable(true);
splitPane.setDividerLocation(200);
}
public void initArgs(String [] args)
{
if(args.length > 0) {
String urlStr = null;
if(args[0].equals("-f")) {
if(args.length > 1) {
File inFile = new File(args[1]);
try {
URL url = inFile.toURL();
urlStr = url.toString();
} catch (Exception e) {
e.printStackTrace();
urlStr = null;
}
}
} else if(args[0].equals("-r")) {
if(args.length > 1) {
ClassLoader cl = OTViewer.class.getClassLoader();
URL url = cl.getResource(args[1]);
urlStr = url.toString();
}
} else {
urlStr = args[0];
}
init(urlStr);
} else {
init(null);
}
}
public void init(String url)
{
createActions();
updateMenuBar();
setJMenuBar(menuBar);
bodyPanel = new OTViewContainerPanel(this, null);
bodyPanel.addViewContainerListener(this);
if(showTree) {
dataTreeModel = new SimpleTreeModel();
folderTreeModel = new SimpleTreeModel();
updateTreePane();
getContentPane().add(splitPane);
} else {
getContentPane().add(bodyPanel);
}
SwingUtilities.invokeLater(new Runnable() {
public void run()
{
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
if(screenSize.width < 1000 || screenSize.height < 700) {
setVisible(true);
int state = getExtendedState();
// Set the maximized bits
state |= Frame.MAXIMIZED_BOTH;
// Maximize the frame
setExtendedState(state);
} else {
setBounds(100, 100, 875, 600);
setVisible(true);
}
}
});
if(url != null) {
try {
loadURL(new URL(url));
} catch(Exception e) {
// FIXME: this should popup a dialog
System.err.println("Can't load url");
e.printStackTrace();
return;
}
}
}
private void loadUserDataFile(File file)
{
currentUserFile = file;
try {
loadUserDataURL(file.toURL());
} catch(Exception e) {
e.printStackTrace();
}
}
private void loadUserDataURL(URL url)
throws Exception
{
userDataDB = new XMLDatabase(url);
otrunk.setCreationDb(userDataDB);
// need to set the current user to the one
// defined in this file
OTStateRoot stateRoot = (OTStateRoot)otrunk.getRootObject(userDataDB);
OTObjectMap userMap = stateRoot.getUserMap();
Vector keys = userMap.getObjectKeys();
OTReferenceMap refMap = (OTReferenceMap)userMap.getObject((String)keys.get(0));
currentUser = refMap.getUser();
reloadWindow();
}
private void loadFile(File file)
{
currentAuthoredFile = file;
try {
loadURL(currentAuthoredFile.toURL());
} catch(Exception e) {
e.printStackTrace();
}
}
private void loadURL(URL url)
throws Exception
{
xmlDB = new XMLDatabase(url, System.err);
otrunk = new OTrunkImpl(xmlDB,
new Object [] {new SwingUserMessageHandler(this), new OTUserListService()});
OTViewFactory myViewFactory =
(OTViewFactory)otrunk.getService(OTViewFactory.class);
if(myViewFactory != null) {
otViewFactory = myViewFactory;
}
bodyPanel.setOTViewFactory(otViewFactory);
currentURL = url;
reloadWindow();
}
private void reloadWindow()
throws Exception
{
OTObject root = null;
boolean overrideShowTree = false;
switch(userMode){
case NO_USER_MODE:
root = otrunk.getRoot();
break;
case SINGLE_USER_MODE:
if(userDataDB == null) {
// no user file has been started yet
overrideShowTree = true;
root = otrunk.getFirstObjectNoUserData();
} else {
OTObject otRoot = otrunk.getRoot();
root = otrunk.getUserRuntimeObject(otRoot, currentUser);
}
}
if(showTree && !overrideShowTree) {
OTDataObject rootDataObject = otrunk.getRootDataObject();
dataTreeModel.setRoot(new OTDataObjectNode("root",
otrunk.getRootDataObject(), otrunk));
folderTreeModel.setRoot(new OTFolderNode(root));
}
bodyPanel.setCurrentObject(root, null);
if(showTree && !overrideShowTree) {
folderTreeModel.fireTreeStructureChanged((SimpleTreeNode)folderTreeModel.getRoot());
dataTreeModel.fireTreeStructureChanged((SimpleTreeNode)dataTreeModel.getRoot());
}
Frame frame = (Frame)SwingUtilities.getRoot(this);
switch(userMode) {
case NO_USER_MODE:
frame.setTitle("CCPortfolio: " + currentURL.toString());
break;
case SINGLE_USER_MODE:
if(currentUserFile != null) {
frame.setTitle("CCPortfolio: " + currentUserFile.toString());
} else if(userDataDB != null){
frame.setTitle("CCPortfolio: Untitled");
} else {
frame.setTitle("CCPortfolio");
}
break;
}
saveUserDataAction.setEnabled(userDataDB != null);
saveUserDataAsAction.setEnabled(userDataDB != null);
}
public void reload()
throws Exception
{
loadURL(currentURL);
}
public OTUserObject createUser(String name)
throws Exception
{
OTUserObject user = (OTUserObject)otrunk.createObject(OTUserObject.class);
user.setName(name);
return user;
}
public void setCurrentUser(OTUserObject userObject)
{
OTUserObject oldUser = currentUser;
currentUser = userObject;
if(!currentUser.equals(oldUser)) {
try {
OTObject root = otrunk.getRoot();
if(currentUser != null) {
root = otrunk.getUserRuntimeObject(root, currentUser);
}
if(showTree) {
folderTreeModel.setRoot(new OTFolderNode(root));
}
bodyPanel.setCurrentObject(root, null);
if(showTree) {
folderTreeModel.fireTreeStructureChanged((SimpleTreeNode)folderTreeModel.getRoot());
dataTreeModel.fireTreeStructureChanged((SimpleTreeNode)dataTreeModel.getRoot());
}
userDataDB.setDirty(false);
} catch (Exception e) {
e.printStackTrace();
}
}
}
public static void main(String [] args)
{
System.setProperty("apple.laf.useScreenMenuBar","true");
OTViewer viewer = new OTViewer(true);
if(Boolean.getBoolean("otrunk.view.single_user")) {
viewer.setUserMode(OTViewer.SINGLE_USER_MODE);
}
viewer.initArgs(args);
}
class ExitAction extends AbstractAction
{
public ExitAction()
{
super("Exit");
}
public void actionPerformed(ActionEvent e)
{
// If this suceeds then the VM will exit so
// the window will get disposed
exit();
}
}
/* (non-Javadoc)
* @see org.concord.otrunk.view.OTViewContainerListener#currentObjectChanged(org.concord.framework.otrunk.view.OTViewContainer)
*/
public void currentObjectChanged(OTViewContainer container)
{
// TODO Auto-generated method stub
OTObject currentObject = container.getCurrentObject();
if(folderTreeArea != null) {
OTFolderNode node = (OTFolderNode)folderTreeArea.getLastSelectedPathComponent();
if(node == null) return;
if(node.getPfObject() != currentObject) {
folderTreeArea.setSelectionPath(null);
}
}
}
/* (non-Javadoc)
* @see javax.swing.event.TreeSelectionListener#valueChanged(javax.swing.event.TreeSelectionEvent)
*/
public void valueChanged(TreeSelectionEvent event)
{
if (event.getSource() == folderTreeArea) {
OTFolderNode node = (OTFolderNode)
folderTreeArea.getLastSelectedPathComponent();
if (node == null) return;
OTObject pfObject = node.getPfObject();
bodyPanel.setCurrentObject(pfObject, null);
if(splitPane.getRightComponent() != bodyPanel){
splitPane.setRightComponent(bodyPanel);
}
} else if (event.getSource() == dataTreeArea) {
SimpleTreeNode node = (SimpleTreeNode)
dataTreeArea.getLastSelectedPathComponent();
Object resourceValue = null;
if(node != null) {
resourceValue = node.getObject();
if(resourceValue == null) {
resourceValue = "null resource value";
}
} else {
resourceValue = "no selected data object";
}
JTextArea textArea = new JTextArea(resourceValue.toString());
splitPane.setRightComponent(textArea);
}
}
public void setFrameObject(OTObject otObject, OTFrame otFrame)
{
// look up view container with the frame.
OTViewContainerPanel otContainer = (OTViewContainerPanel)otContainers.get(otFrame.getGlobalId());
if(otContainer == null) {
JFrame jFrame = new JFrame(otFrame.getTitle());
otContainer = new OTViewContainerPanel(this, jFrame);
otContainer.setOTViewFactory(otViewFactory);
jFrame.getContentPane().setLayout(new BorderLayout());
jFrame.getContentPane().add(otContainer, BorderLayout.CENTER);
jFrame.setSize(otFrame.getWidth(), otFrame.getHeight());
otContainers.put(otFrame.getGlobalId(), otContainer);
}
// call setCurrentObject on that view container with a null
// frame
otContainer.setCurrentObject(otObject, null);
otContainer.showFrame();
}
public void createActions()
{
newUserDataAction = new AbstractAction(){
/* (non-Javadoc)
* @see java.awt.event.ActionListener#actionPerformed(java.awt.event.ActionEvent)
*/
public void actionPerformed(ActionEvent arg0)
{
if(!checkForUnsavedUserData()) {
// the user canceled the operation
return;
}
// call some new method for creating a new un-saved user state
// this should set the currentUserFile to null, so the save check prompts
// for a file name
newAnonUserData();
}
};
newUserDataAction.putValue(Action.NAME, "New");
loadUserDataAction = new AbstractAction(){
/* (non-Javadoc)
* @see java.awt.event.ActionListener#actionPerformed(java.awt.event.ActionEvent)
*/
public void actionPerformed(ActionEvent arg0)
{
if(!checkForUnsavedUserData()) {
// the user canceled the operation
return;
}
Frame frame = (Frame)SwingUtilities.getRoot(OTViewer.this);
FileDialog dialog = new FileDialog(frame, "Open", FileDialog.LOAD);
if(currentUserFile != null) {
dialog.setDirectory(currentUserFile.getParentFile().getAbsolutePath());
dialog.setFile(currentUserFile.getName());
}
dialog.show();
String fileName = dialog.getFile();
if(fileName == null) {
return;
}
fileName = dialog.getDirectory() + fileName;
System.out.println("load file name: " + fileName);
loadUserDataFile(new File(fileName));
}
};
loadUserDataAction.putValue(Action.NAME, "Open...");
saveUserDataAction = new AbstractAction(){
/* (non-Javadoc)
* @see java.awt.event.ActionListener#actionPerformed(java.awt.event.ActionEvent)
*/
public void actionPerformed(ActionEvent arg0)
{
if(currentUserFile == null || !currentUserFile.exists()){
saveUserDataAsAction.actionPerformed(arg0);
return;
}
if(currentUserFile.exists()){
try {
Exporter.export(currentUserFile, userDataDB.getRoot(), userDataDB);
userDataDB.setDirty(false);
} catch(Exception e){
e.printStackTrace();
}
}
}
};
saveUserDataAction.putValue(Action.NAME, "Save");
saveUserDataAsAction = new AbstractAction(){
/* (non-Javadoc)
* @see java.awt.event.ActionListener#actionPerformed(java.awt.event.ActionEvent)
*/
public void actionPerformed(ActionEvent arg0)
{
Frame frame = (Frame)SwingUtilities.getRoot(OTViewer.this);
FileDialog dialog = new FileDialog(frame, "Save As", FileDialog.SAVE);
if(currentUserFile != null) {
dialog.setDirectory(currentUserFile.getParentFile().getAbsolutePath());
dialog.setFile(currentUserFile.getName());
}
dialog.show();
String fileName = dialog.getFile();
if(fileName == null) {
return;
}
fileName = dialog.getDirectory() + fileName;
currentUserFile = new File(fileName);
if(!fileName.toLowerCase().endsWith(".otml")){
currentUserFile = new File(currentUserFile.getAbsolutePath()+".otml");
}
if(!currentUserFile.exists() || checkForReplace(currentUserFile)){
try {
Exporter.export(currentUserFile, userDataDB.getRoot(), userDataDB);
userDataDB.setDirty(false);
setTitle("CCPortfolio: " + currentUserFile.toString());
} catch(Exception e){
e.printStackTrace();
}
}
}
};
saveUserDataAsAction.putValue(Action.NAME, "Save As...");
loadAction = new AbstractAction(){
/* (non-Javadoc)
* @see java.awt.event.ActionListener#actionPerformed(java.awt.event.ActionEvent)
*/
public void actionPerformed(ActionEvent arg0)
{
Frame frame = (Frame)SwingUtilities.getRoot(OTViewer.this);
FileDialog dialog = new FileDialog(frame, "Open", FileDialog.LOAD);
if(currentAuthoredFile != null) {
dialog.setDirectory(currentAuthoredFile.getParentFile().getAbsolutePath());
dialog.setFile(currentAuthoredFile.getName());
}
dialog.show();
String fileName = dialog.getFile();
if(fileName == null) {
return;
}
fileName = dialog.getDirectory() + fileName;
System.out.println("load file name: " + fileName);
loadFile(new File(fileName));
}
};
loadAction.putValue(Action.NAME, "Open Authored Content...");
saveAction = new AbstractAction(){
/* (non-Javadoc)
* @see java.awt.event.ActionListener#actionPerformed(java.awt.event.ActionEvent)
*/
public void actionPerformed(ActionEvent arg0)
{
if(currentAuthoredFile == null){
saveAsAction.actionPerformed(arg0);
return;
}
if(!currentAuthoredFile.exists() || checkForReplace(currentAuthoredFile)){
try {
Exporter.export(currentAuthoredFile, xmlDB.getRoot(), xmlDB);
} catch(Exception e){
e.printStackTrace();
}
}
}
};
saveAction.putValue(Action.NAME, "Save Authored Content...");
saveAsAction = new AbstractAction(){
/* (non-Javadoc)
* @see java.awt.event.ActionListener#actionPerformed(java.awt.event.ActionEvent)
*/
public void actionPerformed(ActionEvent arg0)
{
Frame frame = (Frame)SwingUtilities.getRoot(OTViewer.this);
FileDialog dialog = new FileDialog(frame, "Save As", FileDialog.SAVE);
if(currentAuthoredFile != null) {
dialog.setDirectory(currentAuthoredFile.getParentFile().getAbsolutePath());
dialog.setFile(currentAuthoredFile.getName());
}
dialog.show();
String fileName = dialog.getFile();
if(fileName == null) {
return;
}
fileName = dialog.getDirectory() + fileName;
currentAuthoredFile = new File(fileName);
if(!fileName.toLowerCase().endsWith(".otml")){
currentAuthoredFile = new File(currentAuthoredFile.getAbsolutePath()+".otml");
}
if(!currentAuthoredFile.exists() || checkForReplace(currentAuthoredFile)){
try {
Exporter.export(currentAuthoredFile, xmlDB.getRoot(), xmlDB);
} catch(Exception e){
e.printStackTrace();
}
}
frame.setTitle(fileName);
}
};
saveAsAction.putValue(Action.NAME, "Save Authored Content As...");
exportImageAction = new AbstractAction(){
public void actionPerformed(ActionEvent e)
{
// this introduces a dependency on concord Swing project
// instead there needs to be a way to added these actions through
// the xml
Component currentComp = bodyPanel.getCurrentComponent();
if(currentComp instanceof JScrollPane) {
currentComp = ((JScrollPane)currentComp).getViewport().getView();
}
Util.makeScreenShot(currentComp);
}
};
exportImageAction.putValue(Action.NAME, "Export Image...");
exportHiResImageAction = new AbstractAction(){
public void actionPerformed(ActionEvent e)
{
Component currentComp = bodyPanel.getCurrentComponent();
if(currentComp instanceof JScrollPane) {
currentComp = ((JScrollPane)currentComp).getViewport().getView();
}
Util.makeScreenShot(currentComp, 2, 2);
}
};
exportHiResImageAction.putValue(Action.NAME, "Export Hi Res Image...");
debugAction = new AbstractAction(){
public void actionPerformed(ActionEvent e)
{
Object source = e.getSource();
if(((JCheckBoxMenuItem)source).isSelected()){
System.setProperty("otrunk.view.debug","true");
} else {
System.setProperty("otrunk.view.debug","false");
}
updateTreePane();
SwingUtilities.invokeLater(new Runnable(){
public void run()
{
updateMenuBar();
}
});
}
};
debugAction.putValue(Action.NAME, "Debug Mode");
exitAction = new ExitAction();
}
/**
* @return Returns the menuBar.
*/
public JMenuBar updateMenuBar()
{
JMenu fileMenu = null;
if (menuBar == null){
menuBar = new JMenuBar();
fileMenu = new JMenu("File");
menuBar.add(fileMenu);
} else {
fileMenu = menuBar.getMenu(0);
fileMenu.removeAll();
}
if(userMode == SINGLE_USER_MODE) {
fileMenu.add(newUserDataAction);
fileMenu.add(loadUserDataAction);
fileMenu.add(saveUserDataAction);
fileMenu.add(saveUserDataAsAction);
}
if(Boolean.getBoolean("otrunk.view.debug")) {
fileMenu.add(loadAction);
fileMenu.add(saveAction);
fileMenu.add(saveAsAction);
}
if(Boolean.getBoolean("otrunk.view.export_image")) {
fileMenu.add(exportImageAction);
fileMenu.add(exportHiResImageAction);
}
JCheckBoxMenuItem debugItem = new JCheckBoxMenuItem(debugAction);
debugItem.setSelected(Boolean.getBoolean("otrunk.view.debug"));
fileMenu.add(debugItem);
fileMenu.add(exitAction);
return menuBar;
}
boolean checkForReplace(File file){
if(file == null || !file.exists()) return false;
final Object[] options = { "Yes", "No" };
return javax.swing.JOptionPane.showOptionDialog(null,
"The file '" + file.getName() +
"' already exists. " +
"Replace existing file?",
"Warning",
javax.swing.JOptionPane.YES_NO_OPTION,
javax.swing.JOptionPane.WARNING_MESSAGE,
null,
options,
options[1]) == javax.swing.JOptionPane.YES_OPTION;
}
/**
* Checks if the user has unsaved work. If they do then it prompts them to
* confirm what they are doing. If they cancel then it returns false.
*
* @return
*/
public boolean checkForUnsavedUserData()
{
if(currentUser != null && userDataDB != null)
{
if(userDataDB.isDirty()) {
// show dialog message telling them they haven't
// saved their work
// FIXME
String options [] = {"Don't Save", "Cancel", "Save"};
int chosenOption = JOptionPane.showOptionDialog(this, "Save Changes?", "Save Changes?",
JOptionPane.DEFAULT_OPTION, JOptionPane.WARNING_MESSAGE,
null, options, options[2]);
switch(chosenOption) {
case 0:
System.err.println("Not saving work");
break;
case 1:
System.err.println("Canceling close");
return false;
case 2:
System.err.println("Saving work");
saveUserDataAction.actionPerformed(null);
break;
}
}
}
return true;
}
/**
* This does not check for unsaved user data
*
*/
public void newAnonUserData()
{
// call some new method for creating a new un-saved user state
// this should set the currentUserFile to null, so the save check prompts
// for a file name
try {
// need to make a brand new stateDB
userDataDB = new XMLDatabase();
otrunk.setCreationDb(userDataDB);
OTStateRoot stateRoot = (OTStateRoot)otrunk.createObject(OTStateRoot.class);
userDataDB.setRoot(stateRoot.getGlobalId());
stateRoot.setFormatVersionString("1.0");
userDataDB.setDirty(false);
OTUserObject userObject = createUser("anon_single_user");
setCurrentUser(userObject);
currentUserFile = null;
reloadWindow();
} catch (Exception e) {
e.printStackTrace();
}
}
public boolean exit()
{
try {
if(!checkForUnsavedUserData()) {
// the user canceled the operation
return false;
}
otrunk.close();
} catch (Exception exp) {
exp.printStackTrace();
// exit anyhow
}
System.exit(0);
return true;
}
} // @jve:decl-index=0:visual-constraint="10,10"
|
package org.concord.otrunk.view;
import java.awt.AWTEvent;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.Frame;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.KeyEventDispatcher;
import java.awt.KeyboardFocusManager;
import java.awt.Point;
import java.awt.Toolkit;
import java.awt.event.AWTEventListener;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.MouseEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.File;
import java.io.PrintStream;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Vector;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JCheckBoxMenuItem;
import javax.swing.JComponent;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JSplitPane;
import javax.swing.JTabbedPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.JTree;
import javax.swing.JWindow;
import javax.swing.KeyStroke;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.WindowConstants;
import javax.swing.border.BevelBorder;
import javax.swing.border.EmptyBorder;
import javax.swing.event.TreeSelectionEvent;
import javax.swing.event.TreeSelectionListener;
import javax.swing.tree.TreePath;
import org.concord.applesupport.AppleApplicationAdapter;
import org.concord.applesupport.AppleApplicationUtil;
import org.concord.framework.otrunk.OTChangeEvent;
import org.concord.framework.otrunk.OTChangeListener;
import org.concord.framework.otrunk.OTID;
import org.concord.framework.otrunk.OTObject;
import org.concord.framework.otrunk.OTObjectList;
import org.concord.framework.otrunk.OTUser;
import org.concord.framework.otrunk.OTrunk;
import org.concord.framework.otrunk.view.OTExternalAppService;
import org.concord.framework.otrunk.view.OTFrameManager;
import org.concord.framework.otrunk.view.OTJComponentServiceFactory;
import org.concord.framework.otrunk.view.OTUserListService;
import org.concord.framework.otrunk.view.OTViewContainer;
import org.concord.framework.otrunk.view.OTViewContainerChangeEvent;
import org.concord.framework.otrunk.view.OTViewContainerListener;
import org.concord.framework.otrunk.view.OTViewContext;
import org.concord.framework.otrunk.view.OTViewFactory;
import org.concord.framework.text.UserMessageHandler;
import org.concord.framework.text.UserMessageHandlerExt1;
import org.concord.framework.util.SimpleTreeNode;
import org.concord.otrunk.OTMLToXHTMLConverter;
import org.concord.otrunk.OTSystem;
import org.concord.otrunk.OTrunkImpl;
import org.concord.otrunk.OTrunkServiceEntry;
import org.concord.otrunk.PageXHTMLExporter;
import org.concord.otrunk.datamodel.OTDataObject;
import org.concord.otrunk.handlers.UrlStreamHandlerFactory;
import org.concord.otrunk.net.HTTPRequestException;
import org.concord.otrunk.overlay.OTOverlayGroup;
import org.concord.otrunk.user.OTUserObject;
import org.concord.otrunk.xml.ExporterJDOM;
import org.concord.otrunk.xml.XMLDatabase;
import org.concord.otrunk.xml.XMLDatabaseChangeEvent;
import org.concord.otrunk.xml.XMLDatabaseChangeListener;
import org.concord.swing.CustomDialog;
import org.concord.swing.MemoryMonitorPanel;
import org.concord.swing.MostRecentFileDialog;
import org.concord.swing.StreamRecord;
import org.concord.swing.StreamRecordView;
import org.concord.swing.util.Util;
import org.concord.utilities.InstallationResponseCache;
import org.concord.view.SimpleTreeModel;
import org.concord.view.SwingUserMessageHandler;
/**
* OTViewer Class name and description
*
* Date created: Dec 14, 2004
*
* @author scott
*
*/
public class OTViewer extends JFrame
implements TreeSelectionListener, OTViewContainerListener, AppleApplicationAdapter
{
/**
* first version of this class
*/
private static final long serialVersionUID = 1L;
private static final Logger logger = Logger.getLogger(OTViewer.class.getCanonicalName());
public final static String TITLE_PROP = "otrunk.view.frame_title";
public final static String HIDE_TREE_PROP = "otrunk.view.hide_tree";
public final static String SHOW_CONSOLE_PROP = "otrunk.view.show_console";
public final static String DEMO_ONLY_PROP = "otrunk.view.demo";
public final static String OTML_URL_PROP = "otrunk.otmlurl";
public final static String HTTP_PUT = "PUT";
public final static String HTTP_POST = "POST";
public final static String HTTP_HEAD = "HEAD";
final static String DEFAULT_BASE_FRAME_TITLE = "OTrunk Viewer";
private static OTViewFactory otViewFactory;
OTFrameManagerImpl frameManager;
JSplitPane splitPane;
OTViewContainerPanel bodyPanel;
SimpleTreeModel folderTreeModel;
SimpleTreeModel dataTreeModel;
JTree folderTreeArea;
JTree dataTreeArea;
/**
* Dialog used for instruction panel that shows when the program starts
* Prompts "new" or "open" portfolio
*/
private JDialog commDialog;
private static JFrame consoleFrame;
JMenuBar menuBar;
private JPanel statusPanel;
String baseFrameTitle;
boolean showTree = false;
private boolean useScrollPane;
boolean justStarted = false;
protected int userMode = OTConfig.NO_USER_MODE;
File currentAuthoredFile = null;
URL currentURL = null;
URL remoteURL;
OTUserSession userSession;
private static OTrunkImpl otrunk;
XMLDatabase xmlDB;
private OTSystem userSystem;
private ArrayList<OTrunkServiceEntry<?>> services =
new ArrayList<OTrunkServiceEntry<?>>();
private OTChangeListener systemChangeListener;
/**
* This is true if the user was asked about saving user data after they
* initiated a close of the current view.
*/
private boolean askedAboutSavingUserData = false;
/**
* This is true if the user was asked about saving the user data, and said
* yes
*/
private boolean needToSaveUserData = false;
/**
* This is true if the SailOTViewer created this OTViewer
*/
private boolean launchedBySailOTViewer = false;
private boolean sailSaveEnabled = true;
// Temp, to close the window
AbstractAction exitAction;
AbstractAction saveAsAction;
private AbstractAction saveUserDataAsAction;
private AbstractAction saveUserDataAction;
private AbstractAction debugAction;
private AbstractAction showConsoleAction;
private AbstractAction newUserDataAction;
private AbstractAction loadUserDataAction;
private AbstractAction loadAction;
private AbstractAction reloadWindowAction;
private AbstractAction saveAction;
private AbstractAction saveRemoteAsAction;
private AbstractAction exportImageAction;
private AbstractAction exportHiResImageAction;
private AbstractAction exportToHtmlAction;
private AbstractAction exportCurrentToHtmlAction;
private boolean settingUp;
public OTViewer() {
super();
if (OTConfig.isSingleUserMode()) {
InstallationResponseCache.installResponseCache();
}
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (Exception e) {
logger.warning("Error setting native LAF: " + e);
}
this.showTree = true;
AppleApplicationUtil.registerWithMacOSX(this);
baseFrameTitle = DEFAULT_BASE_FRAME_TITLE;
try {
// this overrides the default base frame title
String title = System.getProperty(TITLE_PROP, null);
if (title != null) {
baseFrameTitle = title;
}
} catch (Throwable t) {
// do nothing, just use the default title
}
setTitle(baseFrameTitle);
// If "otrunk.view.demo" is true, closing frame will just dispose
// the frame, not exit.
if (!Boolean.getBoolean(DEMO_ONLY_PROP)){
setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE);
addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e)
{
exitAction.actionPerformed(null);
}
});
}
commDialog = new JDialog(this, true);
registerDebugEventListeners();
}
private static void createConsoleFrame() {
if (consoleFrame == null) {
consoleFrame = new JFrame("Console");
StreamRecord record = new StreamRecord(50000);
StreamRecordView view = new StreamRecordView(record);
consoleFrame.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
System.setOut((PrintStream) view.addOutputStream(System.out, "Console"));
System.setErr((PrintStream) view.addOutputStream(System.err, System.out));
consoleFrame.getContentPane().add(view);
consoleFrame.setSize(800, 600);
if (OTConfig.getBooleanProp(SHOW_CONSOLE_PROP, false)) {
consoleFrame.setVisible(true);
}
}
}
public static void setConsoleFrame(JFrame frame) {
consoleFrame = frame;
}
private void registerDebugEventListeners() {
// for debugging
// add a breakpoint below, run in debugging mode, and then hit Meta-B
// the object you're currently focused on will be passed in here and you
// can
// start exploring the data structures, etc.
KeyboardFocusManager focusManager =
KeyboardFocusManager.getCurrentKeyboardFocusManager();
KeyEventDispatcher deleteDispatcher = new KeyEventDispatcher(){
public boolean dispatchKeyEvent(KeyEvent e)
{
if ((e.getID() == java.awt.event.KeyEvent.KEY_RELEASED)
&& ((e.getModifiersEx() & java.awt.event.InputEvent.META_DOWN_MASK) != 0)
&& (e.getKeyCode() == java.awt.event.KeyEvent.VK_B)) {
Object o = e.getSource();
logger.fine(o.toString());
return true;
}
return false;
}
};
focusManager.addKeyEventDispatcher(deleteDispatcher);
// If the mouse click is a right click event and alt is pressed
// or on a Mac the ctrl and option keys are down
// then this code will print out the toString method of the
// object which the mouse is over to the console.
AWTEventListener awtEventListener = new AWTEventListener(){
public void eventDispatched(AWTEvent event)
{
if(!(event instanceof MouseEvent)){
return;
}
MouseEvent mEvent = (MouseEvent) event;
if (mEvent.getID() == MouseEvent.MOUSE_CLICKED
&& (mEvent.getModifiersEx() & MouseEvent.ALT_DOWN_MASK) != 0) {
logger.info(event.getSource().toString());
}
}
};
Toolkit.getDefaultToolkit().addAWTEventListener(awtEventListener,
AWTEvent.MOUSE_EVENT_MASK);
}
/**
* this needs to be called before initialized.
*
* @param serviceInterface
* @param service
*/
public <T> void addService(Class<T> serviceInterface, T service)
{
OTrunkServiceEntry<T> entry = new OTrunkServiceEntry<T>(service, serviceInterface);
services.add(entry);
}
public void setUserMode(int mode)
{
userMode = mode;
}
public int getUserMode()
{
return userMode;
}
public void updateTreePane()
{
Dimension minimumSize = new Dimension(100, 50);
folderTreeArea = new JTree(folderTreeModel);
// we are just disabling this however if we want to
// use this tree for authoring, or for managing student
// created objects this will need to be some form of option
folderTreeArea.setEditable(false);
folderTreeArea.addTreeSelectionListener(this);
JComponent leftComponent = null;
JScrollPane folderTreeScrollPane = new JScrollPane(folderTreeArea);
if (System.getProperty(OTConfig.DEBUG_PROP, "").equals("true")) {
// ViewFactory.getComponent(root);
dataTreeArea = new JTree(dataTreeModel);
dataTreeArea.setEditable(false);
dataTreeArea.addTreeSelectionListener(this);
JScrollPane dataTreeScrollPane = new JScrollPane(dataTreeArea);
JTabbedPane tabbedPane = new JTabbedPane();
tabbedPane.add("Folders", folderTreeScrollPane);
tabbedPane.add("Resources", dataTreeScrollPane);
// Provide minimum sizes for the two components in the split pane
folderTreeScrollPane.setMinimumSize(minimumSize);
dataTreeScrollPane.setMinimumSize(minimumSize);
tabbedPane.setMinimumSize(minimumSize);
leftComponent = tabbedPane;
} else {
leftComponent = folderTreeScrollPane;
}
if (splitPane == null) {
splitPane =
new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, leftComponent, bodyPanel);
} else {
splitPane.setLeftComponent(leftComponent);
}
splitPane.setOneTouchExpandable(true);
splitPane.setDividerLocation(200);
}
public void initArgs(String[] args) {
URL authorOTMLURL = OTViewerHelper.getURLFromArgs(args);
if (authorOTMLURL == null && System.getProperty(OTML_URL_PROP, null) != null) {
try {
authorOTMLURL = new URL(System.getProperty(OTML_URL_PROP, null));
} catch (MalformedURLException e) {
e.printStackTrace();
}
}
if (authorOTMLURL == null) {
authorOTMLURL = OTViewer.class.getResource("no-arguments-page.otml");
}
initWithWizard(authorOTMLURL);
}
/**
* @param args
* @return
*/
public String getURL(String[] args)
{
URL authorOTMLURL = OTViewerHelper.getURLFromArgs(args);
if ("file".equalsIgnoreCase(authorOTMLURL.getProtocol())) {
try {
URI authorOTMLURI = new URI(authorOTMLURL.toString());
currentAuthoredFile = new File(authorOTMLURI);
} catch (URISyntaxException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return authorOTMLURL.toString();
}
// private static Object getURLStreamHandlerFactoryLock()
// Object lock;
// try {
// Field streamHandlerLockField = URL.class.getDeclaredField("streamHandlerLock"); //$NON-NLS-1$
// streamHandlerLockField.setAccessible(true);
// lock = streamHandlerLockField.get(null);
// } catch (NoSuchFieldException noField) {
// // could not find the lock, lets sync on the class object
// lock = URL.class;
// return lock;
private void registerURLStreamHandlers(){
try {
UrlStreamHandlerFactory.registerHandlerClass(org.concord.otrunk.handlers.jres.Handler.class);
} catch (Exception e){
// don't do anything here. If SailStreamHandlerFactory has already been
// created, SailOTViewer should have already added the handlers
}
/*
* If we wanted to do something clever at a later date, the reflection code below would
* allow us to get the current URLStreamHandlerFactory
*/
// Field factoryField = null;
// Field[] fields = URL.class.getDeclaredFields();
// for (int i = 0; i < fields.length; i++) {
// if (Modifier.isStatic(fields[i].getModifiers())
// && fields[i].getType().equals(URLStreamHandlerFactory.class)) {
// factoryField = fields[i];
// break;
// factoryField.setAccessible(true);
// try {
// URLStreamHandlerFactory factory = (URLStreamHandlerFactory) factoryField.get(null);
// if (factory == null){
// UrlStreamHandlerFactory.registerHandlerClass(org.concord.otrunk.handlers.jres.Handler.class);
// } catch (Exception e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
}
public boolean init(String url)
{
try {
return init(new URL(url));
} catch (MalformedURLException e) {
e.printStackTrace();
}
return false;
}
/**
*
* @param url
* @return true if the url was loaded, return false if an error happens and it wasn't loaded
*/
public boolean init(URL url) {
registerURLStreamHandlers();
updateRemoteURL(url.toExternalForm());
createActions();
updateMenuBar();
setJMenuBar(menuBar);
frameManager = new OTFrameManagerImpl();
frameManager.setMainFrame(this);
bodyPanel = new OTViewContainerPanel(frameManager);
bodyPanel.addViewContainerListener(this);
if (showTree) {
dataTreeModel = new SimpleTreeModel();
folderTreeModel = new SimpleTreeModel();
updateTreePane();
getContentPane().add(splitPane);
} else {
getContentPane().add(bodyPanel);
}
if (OTConfig.isShowStatus() || noClassAssignedForStudent()) {
initStatusBar();
}
initFrameDimensions();
if (url == null) {
return false;
}
try {
initializeURL(url);
} catch (MalformedURLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (Exception e) {
// FIXME: this should popup a dialog
logger.log(Level.SEVERE, "Can't load url", e);
return false;
}
return true;
}
/*
* Test to determine whether to display warning that the student may not
* be running the activity with correct portal settings.
*
* Shoud return true when the activity is not run in student mode and
* is not assigned a class and a teacher through the portal.
*/
private boolean noClassAssignedForStudent() {
return getUserMode() == OTConfig.SINGLE_USER_MODE && ! isSailSaveEnabled();
}
private Point bottomCorner;
public void setStatusPanelVisible(boolean visible) {
if (visible) {
if (statusPanel == null) {
// wants to be visible, but hasn't been set up yet
initStatusBar();
}
}
if (statusPanel != null) {
statusPanel.setVisible(visible);
}
}
public JPanel getStatusPanel() {
return this.statusPanel;
}
private void initStatusBar() {
statusPanel = new JPanel(new FlowLayout(FlowLayout.TRAILING, 3, 1));
if (OTConfig.isShowStatus()) {
final JLabel saveStateLabel = new JLabel("File saved");
statusPanel.add(saveStateLabel);
statusPanel.add(Box.createHorizontalStrut(20));
statusPanel.add(new MemoryMonitorPanel());
statusPanel.add(Box.createHorizontalStrut(5));
// It takes a while for xmlDM to be initialized...
Thread waitForDB = new Thread() {
@Override
public void run()
{
while (xmlDB == null) {
try {
sleep(1000);
} catch (Exception e) {
}
}
xmlDB.addXMLDatabaseChangeListener(new XMLDatabaseChangeListener() {
public void stateChanged(XMLDatabaseChangeEvent e)
{
if (xmlDB.isDirty()) {
saveStateLabel.setText("Unsaved changes");
} else {
saveStateLabel.setText("File saved");
if (!settingUp){
// show save confirmation dialog
final JWindow savedWindow = new JWindow();
JLabel savedLabel = new JLabel("File saved");
savedLabel.setFont(saveStateLabel.getFont().deriveFont(Font.BOLD));
String fileName = currentAuthoredFile.getAbsolutePath();
if (fileName.length() > 35){
fileName = "... "+fileName.substring(fileName.length()-35);
}
JLabel locationLabel = new JLabel(fileName);
locationLabel.setBorder(BorderFactory.createCompoundBorder(
BorderFactory.createLineBorder(Color.BLACK),
BorderFactory.createEmptyBorder(3, 3, 3, 3)));
final JPanel savedPanel = new JPanel(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.insets = new Insets(8, 8, 8, 8);
gbc.gridwidth = GridBagConstraints.REMAINDER;
savedPanel.add(savedLabel, gbc);
savedPanel.add(locationLabel, gbc);
savedPanel.setBorder(BorderFactory.createBevelBorder(BevelBorder.RAISED));
savedWindow.add(savedPanel);
savedWindow.pack();
final int desiredHeight = savedWindow.getHeight();
savedWindow.getContentPane().setLayout(null);
savedWindow.setSize(savedWindow.getWidth(), 0);
bottomCorner = new Point(OTViewer.this.getLocationOnScreen().x + OTViewer.this.getWidth(),
OTViewer.this.getLocationOnScreen().y + OTViewer.this.getHeight());
savedWindow.setLocation(bottomCorner.x - savedWindow.getWidth(), bottomCorner.y);
savedWindow.setVisible(true);
javax.swing.Timer timer = new javax.swing.Timer(0, new ActionListener() {
public void actionPerformed(ActionEvent e) {
int newHeight = Math.min(savedWindow.getHeight()+6, desiredHeight);
savedWindow.setSize(savedWindow.getWidth(),newHeight);
savedWindow.setLocation(bottomCorner.x - savedWindow.getWidth(), bottomCorner.y-savedWindow.getHeight());
savedPanel.repaint();
if(newHeight >= desiredHeight) {
((javax.swing.Timer) e.getSource()).stop();
//restore original layout
savedWindow.getContentPane().setLayout(new BorderLayout());
savedWindow.validate();
}
}
});
timer.start();
javax.swing.Timer timer2 = new javax.swing.Timer(0, new ActionListener() {
public void actionPerformed(ActionEvent e) {
int newHeight = Math.max(savedWindow.getHeight()-6, 0);
savedWindow.setSize(savedWindow.getWidth(),newHeight);
savedWindow.setLocation(bottomCorner.x - savedWindow.getWidth(), bottomCorner.y-savedWindow.getHeight());
savedPanel.repaint();
if(newHeight <= 0) {
((javax.swing.Timer) e.getSource()).stop();
savedWindow.dispose();
}
}
});
timer2.setInitialDelay(2500);
timer2.start();
// TimerTask closeTask = new TimerTask() {
// @Override
// public void run()
// savedWindow.setVisible(false);
// Timer timer2 = new Timer();
// timer2.schedule(closeTask, 2500);
}
}
statusPanel.repaint();
}
});
}
};
waitForDB.start();
}
if (noClassAssignedForStudent()) {
JLabel readOnlyLabel = new JLabel("User Data Will Not Be Saved!");
statusPanel.setBackground(Color.RED);
statusPanel.add(readOnlyLabel);
statusPanel.add(Box.createHorizontalStrut(5));
}
getContentPane().add(statusPanel, BorderLayout.SOUTH);
}
private void initFrameDimensions() {
SwingUtilities.invokeLater(new Runnable() {
public void run()
{
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
if (screenSize.width < 1000 || screenSize.height < 700) {
setVisible(true);
int state = getExtendedState();
// Set the maximized bits
state |= Frame.MAXIMIZED_BOTH;
// Maximize the frame
setExtendedState(state);
} else {
int cornerX = 50;
int cornerY = 50;
int sizeX = 800;
int sizeY = 500;
// OTViewService viewService = otViewFactory.
setBounds(cornerX, cornerY, cornerX + sizeX, cornerY + sizeY);
setVisible(true);
}
}
});
}
public void initializeURL(URL url)
throws Exception
{
loadURL(url);
otrunk.setSailSavingDisabled(noClassAssignedForStudent());
OTMainFrame mainFrame = otrunk.getService(OTMainFrame.class);
if (OTConfig.getBooleanProp(HIDE_TREE_PROP, false)
|| !mainFrame.getShowLeftPanel()) {
splitPane.getLeftComponent().setVisible(false);
}
useScrollPane = true;
if (mainFrame.getFrame() != null) {
if (mainFrame.getFrame().isResourceSet("openMaximized")
&& mainFrame.getFrame().getOpenMaximized()){
setExtendedState(Frame.MAXIMIZED_BOTH);
} else if (mainFrame.getFrame().isResourceSet("width")
&& mainFrame.getFrame().isResourceSet("height")) {
int cornerX = mainFrame.getFrame().getPositionX();
int cornerY = mainFrame.getFrame().getPositionY();
int sizeX = mainFrame.getFrame().getWidth();
int sizeY = mainFrame.getFrame().getHeight();
// See if title is set for main frame (only if name is
// still default, so that jnlp prop will still
// overrides this)
if (baseFrameTitle == DEFAULT_BASE_FRAME_TITLE &&
mainFrame.getFrame().isResourceSet("title")){
logger.fine("change");
baseFrameTitle = mainFrame.getFrame().getTitle();
setTitle(baseFrameTitle);
}
setBounds(cornerX, cornerY, cornerX + sizeX, cornerY + sizeY);
repaint();
}
useScrollPane = mainFrame.getFrame().getUseScrollPane();
}
bodyPanel.setUseScrollPane(useScrollPane);
setupBodyPanel();
}
public void initWithWizard(String url) {
try {
initWithWizard(new URL(url));
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void initWithWizard(URL url) {
justStarted = true;
init(url);
if (userMode == OTConfig.SINGLE_USER_MODE) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
instructionPanel();
}
});
}
}
public void loadUserDataFile(File file)
{
try {
OTMLUserSession xmlUserSession = new OTMLUserSession(file, null);
loadUserSession(xmlUserSession);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* This method just sets the viewers userSession without loading it.
* This is useful if a user needs to select the data they want to use
* when the load method is called. Currently this is used by the "wizard" in
* the ot viewer.
*
* @param userSession
*/
public void setUserSession(OTUserSession userSession)
{
this.userSession = userSession;
userSession.setOTrunk(otrunk);
}
/**
* This method loads in a user session, and reloads the window.
*
* @param userSession
* @throws Exception
*/
public void loadUserSession(OTUserSession userSession)
throws Exception
{
this.userSession = userSession;
otrunk.registerUserSession(userSession);
reloadWindow();
}
public void updateOverlayGroupListeners()
{
OTObjectList overlays = userSystem.getOverlays();
for(int i=0; i<overlays.size(); i++){
OTObject item = overlays.get(i);
if(item instanceof OTOverlayGroup){
((OTOverlayGroup) item).addOTChangeListener(systemChangeListener);
}
}
}
public void reloadOverlays()
{
try {
otrunk.reloadOverlays(userSession);
updateOverlayGroupListeners();
reloadWindow();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private void loadFile(File file)
{
currentAuthoredFile = file;
try {
initializeURL(currentAuthoredFile.toURL());
} catch (Exception e) {
e.printStackTrace();
}
}
public void loadURL(URL url)
throws Exception
{
if ("file".equalsIgnoreCase(url.getProtocol())) {
currentAuthoredFile = new File(url.getPath());
}
XMLDatabase systemDB = null;
try {
// try loading in the system object if there is one
String systemOtmlUrlStr =
OTConfig.getStringProp(OTConfig.SYSTEM_OTML_PROP);
if(systemOtmlUrlStr != null){
URL systemOtmlUrl = new URL(systemOtmlUrlStr);
systemDB = new XMLDatabase(systemOtmlUrl, true, System.out);
// don't track the resource info on the system db.
systemDB.loadObjects();
}
} catch (Exception e){
e.printStackTrace();
systemDB = null;
}
try {
xmlDB = new XMLDatabase(url, true, System.out);
// Only track the resource info when there isn't a user. Currently
// all classroom uses
// of OTViewer has NO_USER_MODE turned off, so using this setting
// safe to test
// the resource tracking without affecting real users.
if (userMode == OTConfig.NO_USER_MODE) {
xmlDB.setTrackResourceInfo(true);
}
xmlDB.loadObjects();
} catch (org.jdom.input.JDOMParseException e) {
String xmlWarningTitle = "XML Decoding error";
String xmlWarningMessage =
"There appears to a problem parsing the XML of this document. \n"
+ "Please show this error message to one of the workshop leaders. \n\n"
+ e.getMessage();
JOptionPane.showMessageDialog(null, xmlWarningMessage, xmlWarningTitle,
JOptionPane.ERROR_MESSAGE);
throw e;
}
addService(UserMessageHandler.class, new SwingUserMessageHandler(this));
addService(OTViewer.class, this);
otrunk = new OTrunkImpl(systemDB, xmlDB, services);
OTViewFactory myViewFactory =
otrunk.getService(OTViewFactory.class);
if (myViewFactory != null) {
otViewFactory = myViewFactory;
}
OTViewContext factoryContext = otViewFactory.getViewContext();
factoryContext.addViewService(OTrunk.class, otrunk);
factoryContext.addViewService(OTFrameManager.class, frameManager);
factoryContext.addViewService(OTJComponentServiceFactory.class,
new OTJComponentServiceFactoryImpl());
factoryContext.addViewService(OTExternalAppService.class,
new OTExternalAppServiceImpl());
factoryContext.addViewService(OTUserListService.class, new OTUserListService() {
public Vector<OTUser> getUserList() {
return otrunk.getUsers();
}
});
((OTViewFactoryImpl)otViewFactory).contextSetupComplete();
currentURL = url;
}
// This method was refactored out of loadURL
private void setupBodyPanel()
throws Exception
{
bodyPanel.setTopLevelContainer(true);
bodyPanel.setOTViewFactory(otViewFactory);
// set the current mode from the viewservice to the main bodyPanel
// bodyPanel.setViewMode(otViewFactory.getDefaultMode());
// set the viewFactory of the frame manager
frameManager.setViewFactory(otViewFactory);
settingUp = true;
xmlDB.setDirty(false);
reloadWindow();
settingUp = false;
}
public OTObject getAuthoredRoot()
throws Exception
{
String rootLocalId =
OTConfig.getStringProp(OTConfig.ROOT_OBJECT_PROP);
if(rootLocalId != null){
OTID rootID = xmlDB.getOTIDFromLocalID(rootLocalId);
return otrunk.getOTObject(rootID);
}
return otrunk.getRoot();
}
public OTObject getRoot()
throws Exception
{
switch (userMode) {
case OTConfig.NO_USER_MODE:
return getAuthoredRoot();
case OTConfig.SINGLE_USER_MODE:
if (userSession == null) {
return null;
}
OTObject otRoot = getAuthoredRoot();
return otrunk.getUserRuntimeObject(otRoot, getCurrentUser());
}
return null;
}
public void reloadWindow()
throws Exception
{
OTObject root = getRoot();
boolean overrideShowTree = false;
if (userMode == OTConfig.SINGLE_USER_MODE) {
if (root == null) {
// FIXME This is an error
// the newAnonUserData should have been called before this
// method is
// called
// no user file has been started yet
overrideShowTree = true;
} else {
OTObject realRoot = otrunk.getRealRoot();
if (realRoot instanceof OTSystem) {
OTSystem localUserSystem =
(OTSystem) otrunk.getUserRuntimeObject(realRoot, getCurrentUser());
// FIXME there should be a better way than this because we
// have to handle
// multiple users.
if (localUserSystem != userSystem) {
userSystem = localUserSystem;
systemChangeListener = new OTChangeListener() {
public void stateChanged(OTChangeEvent e)
{
if ("overlays".equals(e.getProperty())) {
reloadOverlays();
}
}
};
updateOverlayGroupListeners();
userSystem.addOTChangeListener(systemChangeListener);
}
}
}
}
if (showTree && !overrideShowTree) {
OTDataObject rootDataObject = xmlDB.getRoot();
dataTreeModel.setRoot(new OTDataObjectNode("root", rootDataObject, otrunk));
folderTreeModel.setRoot(new OTFolderNode(root));
}
bodyPanel.setCurrentObject(root);
if (showTree && !overrideShowTree) {
folderTreeModel.fireTreeStructureChanged(new TreePath(
folderTreeModel.getRoot()));
dataTreeModel.fireTreeStructureChanged(new TreePath(
dataTreeModel.getRoot()));
}
Frame frame = (Frame) SwingUtilities.getRoot(this);
switch (userMode) {
case OTConfig.NO_USER_MODE:
if (remoteURL != null) {
frame.setTitle(baseFrameTitle + ": " + remoteURL.toString());
} else {
frame.setTitle(baseFrameTitle + ": " + currentURL.toString());
}
break;
case OTConfig.SINGLE_USER_MODE:
String userSessionLabel = null;
if (userSession != null) {
userSessionLabel = userSession.getLabel();
}
if(userSessionLabel != null){
frame.setTitle(baseFrameTitle + ": " + userSessionLabel);
} else {
frame.setTitle(baseFrameTitle);
}
break;
}
if(userSession == null){
saveUserDataAction.setEnabled(false);
saveUserDataAsAction.setEnabled(false);
} else {
saveUserDataAction.setEnabled(userSession.allowSave());
saveUserDataAsAction.setEnabled(userSession.allowSaveAs());
}
}
public void reload()
throws Exception
{
initializeURL(currentURL);
}
public OTUserSession getUserSession()
{
return userSession;
}
public OTUserObject getCurrentUser()
{
if(userSession == null){
return null;
}
return userSession.getUserObject();
}
/*
* (non-Javadoc)
*
* @see org.concord.otrunk.view.OTViewContainerListener#currentObjectChanged(org.concord.framework.otrunk.view.OTViewContainer)
*/
public void currentObjectChanged(OTViewContainerChangeEvent evt)
{
final OTViewContainer myContainer = (OTViewContainer) evt.getSource();
// TODO Auto-generated method stub
SwingUtilities.invokeLater(new Runnable() {
public void run()
{
OTObject currentObject = myContainer.getCurrentObject();
if (folderTreeArea != null) {
OTFolderNode node =
(OTFolderNode) folderTreeArea.getLastSelectedPathComponent();
if (node == null)
return;
if (node.getPfObject() != currentObject) {
folderTreeArea.setSelectionPath(null);
}
}
}
});
}
/*
* (non-Javadoc)
*
* @see javax.swing.event.TreeSelectionListener#valueChanged(javax.swing.event.TreeSelectionEvent)
*/
public void valueChanged(TreeSelectionEvent event)
{
if (event.getSource() == folderTreeArea) {
OTFolderNode node =
(OTFolderNode) folderTreeArea.getLastSelectedPathComponent();
if (node == null)
return;
OTObject pfObject = node.getPfObject();
bodyPanel.setCurrentObject(pfObject);
if (splitPane.getRightComponent() != bodyPanel) {
splitPane.setRightComponent(bodyPanel);
}
} else if (event.getSource() == dataTreeArea) {
SimpleTreeNode node =
(SimpleTreeNode) dataTreeArea.getLastSelectedPathComponent();
Object resourceValue = null;
if (node != null) {
resourceValue = node.getObject();
if (resourceValue == null) {
resourceValue = "null resource value";
}
} else {
resourceValue = "no selected data object";
}
JComponent nodeView = null;
if (resourceValue instanceof OTDataObject) {
nodeView = new OTDataObjectView((OTDataObject) resourceValue);
} else {
nodeView = new JTextArea(resourceValue.toString());
}
JScrollPane scrollPane = new JScrollPane(nodeView);
splitPane.setRightComponent(scrollPane);
}
}
private void updateRemoteURL(String defaultURL)
{
String remote = System.getProperty(OTConfig.REMOTE_URL_PROP, null);
try {
if (remote == null) {
if (defaultURL != null && defaultURL.startsWith("http:")) {
remoteURL = new URL(defaultURL);
}
} else {
remoteURL = new URL(remote);
}
} catch (Exception e) {
remoteURL = null;
logger.log(Level.WARNING, "Remote URL is invalid.", e);
}
}
/**
* @return Returns the menuBar.
*/
public JMenuBar updateMenuBar()
{
JMenu fileMenu = null;
if (menuBar == null) {
menuBar = new JMenuBar();
fileMenu = new JMenu("File");
menuBar.add(fileMenu);
} else {
fileMenu = menuBar.getMenu(0);
fileMenu.removeAll();
}
// This is a hacky place to override the userMode, but it is currently
// the best place.
if (OTConfig.isAuthorMode() || OTConfig.isNoUserMode()) {
userMode = OTConfig.NO_USER_MODE;
}
if (userMode == OTConfig.SINGLE_USER_MODE) {
fileMenu.setEnabled(!justStarted);
// we add new and load ("open") menu items only if this is NOT launched
// by sail or if otrunk.view.destructive_menu is set to true
if (!isLaunchedBySailOTViewer() || (OTConfig.isShowDestructiveMenuItems())){
fileMenu.add(newUserDataAction);
fileMenu.add(loadUserDataAction);
}
fileMenu.add(saveUserDataAction);
fileMenu.add(saveUserDataAsAction);
}
if (OTConfig.isDebug()) {
if (userMode == OTConfig.SINGLE_USER_MODE) {
loadAction.putValue(Action.NAME, "Open Authored Content...");
saveAction.putValue(Action.NAME, "Save Authored Content");
saveAsAction.putValue(Action.NAME, "Save Authored Content As...");
saveRemoteAsAction.putValue(Action.NAME,
"Save Authored Content Remotely As...");
} else {
loadAction.putValue(Action.NAME, "Open...");
saveAction.putValue(Action.NAME, "Save");
saveAsAction.putValue(Action.NAME, "Save As...");
saveRemoteAsAction.putValue(Action.NAME, "Save Remotely As...");
}
fileMenu.add(loadAction);
fileMenu.add(saveAction);
fileMenu.add(saveAsAction);
fileMenu.add(saveRemoteAsAction);
}
if (OTConfig.isAuthorMode() && !OTConfig.isDebug()) {
if (userMode == OTConfig.SINGLE_USER_MODE) {
loadAction.putValue(Action.NAME, "Open Authored Content...");
saveAction.putValue(Action.NAME, "Save Authored Content");
saveAsAction.putValue(Action.NAME, "Save Authored Content As...");
} else {
loadAction.putValue(Action.NAME, "Open...");
saveAction.putValue(Action.NAME, "Save");
saveAsAction.putValue(Action.NAME, "Save As...");
}
fileMenu.add(loadAction);
fileMenu.add(saveAction);
fileMenu.add(saveAsAction);
}
if (OTConfig.getBooleanProp("otrunk.view.export_image", false)) {
fileMenu.add(exportImageAction);
fileMenu.add(exportHiResImageAction);
}
if (OTConfig.isUseAlternativeExport()) {
exportCurrentToHtmlAction.putValue(Action.NAME, exportToHtmlAction.getValue(Action.NAME));
fileMenu.add(exportCurrentToHtmlAction);
} else {
fileMenu.add(exportToHtmlAction);
}
fileMenu.add(showConsoleAction);
if (userMode == OTConfig.NO_USER_MODE || OTConfig.isDebug()) {
fileMenu.add(reloadWindowAction);
}
JCheckBoxMenuItem debugItem = new JCheckBoxMenuItem(debugAction);
debugItem.setSelected(OTConfig.isDebug());
fileMenu.add(debugItem);
fileMenu.add(exitAction);
return menuBar;
}
boolean checkForReplace(File file)
{
if (file == null){
return false;
}
if (!file.exists()) {
return true; // File doesn't exist, so go ahead and save
}
if (currentAuthoredFile != null && file.compareTo(currentAuthoredFile) == 0){
return true; // we're already authoring this file, so no need to
// prompt
}
final Object[] options = { "Yes", "No" };
return javax.swing.JOptionPane.showOptionDialog(null, "The file '"
+ file.getName() + "' already exists. " + "Replace existing file?",
"Warning", javax.swing.JOptionPane.YES_NO_OPTION,
javax.swing.JOptionPane.WARNING_MESSAGE, null, options, options[1]) == javax.swing.JOptionPane.YES_OPTION;
}
/**
* FIXME This method name is confusing. The method first checks for unsaved
* changes, and if there are unsaved changes it asks the user if they want to
* "don't save", "cancel" or "save"
*
* @return
*/
public boolean checkForUnsavedUserData()
{
if(userSession == null){
return true;
}
if(userSession.hasUnsavedChanges()) {
// show dialog message telling them they haven't
// saved their work
// FIXME
String options[] = { "Don't Save", "Cancel", "Save" };
askedAboutSavingUserData = true;
int chosenOption =
JOptionPane.showOptionDialog(this, "Save Changes?", "Save Changes?",
JOptionPane.DEFAULT_OPTION, JOptionPane.WARNING_MESSAGE, null,
options, options[2]);
switch (chosenOption) {
case 0:
logger.info("Not saving work");
break;
case 1:
logger.info("Canceling close");
return false;
case 2:
logger.info("Set needToSaveUserData true");
needToSaveUserData = true;
break;
}
}
return true;
}
/**
* Checks if the user has unsaved authored data. If they do then it prompts
* them to confirm what they are doing. If they cancel then it returns
* false.
*
* @return
*/
public boolean checkForUnsavedAuthorData()
{
if (xmlDB != null) {
if (xmlDB.isDirty()) {
// show dialog message telling them they haven't
// saved their work
// FIXME
String options[] = { "Don't Save", "Cancel", "Save" };
int chosenOption =
JOptionPane.showOptionDialog(this, "Save Changes?", "Save Changes?",
JOptionPane.DEFAULT_OPTION, JOptionPane.WARNING_MESSAGE, null,
options, options[2]);
switch (chosenOption) {
case 0:
logger.info("Not saving authored data");
break;
case 1:
logger.info("Canceling close");
return false;
case 2:
logger.info("Saving authored data");
saveAction.actionPerformed(null);
// check again if the save was successful
// it is possible there was an error and the save was unsuccessful.
return checkForUnsavedAuthorData();
}
}
}
return true;
}
/**
* This does not check for unsaved user data
*
*/
public void newAnonUserData()
{
newUserData(OTViewerHelper.ANON_SINGLE_USER_NAME);
}
public void newUserData(String userName)
{
// call some new method for creating a new un-saved user state
// this should set the currentUserFile to null, so the save check
// prompts
// for a file name
if(userSession == null) {
throw new IllegalStateException("a OTUserSession must be supplied before newUserData can be called");
}
try {
userSession.newLayer();
OTUserObject userObject = userSession.getUserObject();
if(userName != null){
userObject.setName(userName);
}
// This will request the label from the userSession
reloadWindow();
} catch (Exception e) {
e.printStackTrace();
}
}
public boolean exit()
{
try {
if (!checkForUnsavedUserData()) {
// the user canceled the operation
return false;
}
if (OTConfig.isAuthorMode() && !checkForUnsavedAuthorData()) {
// the user canceled the operation
return false;
}
// FIXME there is a problem with this logic. If the user saved data
// just before closing
// checkForUnsavedUserData will not see any unsaved data. But if
// some view creates
// data in the viewClosed method then that data will not get saved
// here.
// I think the key to solving this is to separate the
// automatic/logging data from the
// user visible data. And then make a rule that saving data in the
// viewClosed method
// is not allowed.
bodyPanel.setCurrentObject(null);
conditionalSaveUserData();
if (otrunk != null)
otrunk.close();
} catch (Exception exp) {
exp.printStackTrace();
// exit anyhow
}
System.exit(0);
return true;
}
protected void conditionalSaveUserData()
{
if (!askedAboutSavingUserData) {
checkForUnsavedUserData();
}
if (needToSaveUserData) {
saveUserDataAction.actionPerformed(null);
} else {
logger.info("Not saving work before closing.");
}
// Reset these back to false, so if the user is switching to a new
// user or loading a new file we are in a clean state, for that file or
// user
askedAboutSavingUserData = false;
needToSaveUserData = false;
}
public File getReportFile()
{
Frame frame = (Frame) SwingUtilities.getRoot(OTViewer.this);
MostRecentFileDialog mrfd =
new MostRecentFileDialog("org.concord.otviewer.saveotml");
mrfd.setFilenameFilter("html");
if (userSession instanceof OTMLUserSession){
OTMLUserSession otmlUserSession = (OTMLUserSession) userSession;
if(otmlUserSession.currentUserFile != null){
mrfd.setCurrentDirectory(otmlUserSession.currentUserFile.getParentFile());
}
}
int retval = mrfd.showSaveDialog(frame);
File file = null;
if (retval == MostRecentFileDialog.APPROVE_OPTION) {
file = mrfd.getSelectedFile();
String fileName = file.getPath();
if (!fileName.toLowerCase().endsWith(".html")) {
file = new File(file.getAbsolutePath() + ".html");
}
return file;
}
return null;
}
public void createNewUser()
{
if (!checkForUnsavedUserData()) {
// the user canceled the operation
return;
}
// This ensures viewClosed is called
bodyPanel.setCurrentObject(null);
conditionalSaveUserData();
// call some new method for creating a new un-saved user state
// this should set the currentUserFile to null, so the save check
// prompts
// for a file name
newAnonUserData();
exportToHtmlAction.setEnabled(true);
}
public void openUserData(boolean saveCurrentData)
{
if(saveCurrentData){
if (!checkForUnsavedUserData()) {
// the user canceled the operation
return;
}
// FIXME Calling the method below would insure the view is closed, and
// that any data that is
// is modified in that view closed operation will get saved, however if
// the user
// cancels the open dialog then we would be left in an unknown
// state. The current view would be closed which they would want to see
// again.
// bodyPanel.setCurrentObject(null);
conditionalSaveUserData();
}
if(userSession == null){
throw new IllegalStateException("can't open user data without a userSession");
}
boolean success = userSession.open();
try {
reloadWindow();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if(success){
exportToHtmlAction.setEnabled(true);
}
}
public void instructionPanel()
{
commDialog.setResizable(false);
JPanel panel = new JPanel();
panel.setBackground(Color.WHITE);
panel.setLayout(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
c.fill = GridBagConstraints.HORIZONTAL;
c.weightx = 0.5;
c.insets = new Insets(5,10,5,10);
JLabel lNew = new JLabel("Click the \"New\" button to create a new portfolio:");
JLabel lOpen = new JLabel("Click the \"Open\" button to open a saved portfolio:");
JButton bNew = new JButton("New");
JButton bOpen = new JButton("Open");
c.gridx = 0;
c.gridy = 0;
panel.add(lNew, c);
c.gridx = 1;
panel.add(bNew, c);
c.gridx = 0;
c.gridy = 1;
panel.add(lOpen, c);
c.gridx = 1;
panel.add(bOpen, c);
bNew.setOpaque(false);
bOpen.setOpaque(false);
setUserSession(new OTMLUserSession());
bNew.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
commDialog.setVisible(false);
newAnonUserData();
exportToHtmlAction.setEnabled(true);
}
});
bOpen.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
commDialog.setVisible(false);
openUserData(false);
}
});
commDialog.getContentPane().add(panel);
commDialog.setBounds(200, 200, 450, 200);
SwingUtilities.invokeLater(new Runnable() {
public void run()
{
commDialog.setVisible(true);
justStarted = false;
updateMenuBar();
}
});
}
public OTViewContainerPanel getViewContainerPanel()
{
return this.bodyPanel;
}
public void setExitAction(AbstractAction exitAction)
{
this.exitAction = exitAction;
}
/*
* (non-Javadoc)
*
* @see org.concord.applesupport.AppleApplicationAdapter#about()
*/
public void about()
{
// TODO Auto-generated method stub
}
/*
* (non-Javadoc)
*
* @see org.concord.applesupport.AppleApplicationAdapter#preferences()
*/
public void preferences()
{
// TODO Auto-generated method stub
}
public void setLaunchedBySailOTViewer(boolean launchedBySailOTViewer){
this.launchedBySailOTViewer = launchedBySailOTViewer;
}
public boolean isLaunchedBySailOTViewer(){
return launchedBySailOTViewer;
}
/*
* (non-Javadoc)
*
* @see org.concord.applesupport.AppleApplicationAdapter#quit()
*/
public void quit()
{
exitAction.actionPerformed(null);
}
public OTrunk getOTrunk()
{
return otrunk;
}
/**
* @param sailSaveEnabled the sailSaveEnabled to set
*/
public void setSailSaveEnabled(boolean sailSaveEnabled)
{
this.sailSaveEnabled = sailSaveEnabled;
}
/**
* True is sail saving is enabled
* @return the sailSaveEnabled
*/
public boolean isSailSaveEnabled()
{
return sailSaveEnabled;
}
public static void setOTViewFactory(OTViewFactory factory) {
otViewFactory = factory;
}
public void createActions() {
newUserDataAction = new AbstractAction("New") {
/**
* nothing to serialize here
*/
private static final long serialVersionUID = 1L;
/*
* (non-Javadoc)
*
* @see java.awt.event.ActionListener#actionPerformed(java.awt.event.ActionEvent)
*/
public void actionPerformed(ActionEvent arg0)
{
createNewUser();
}
};
loadUserDataAction = new AbstractAction("Open...") {
/**
* nothing to serialize here. Just the parent class.
*/
private static final long serialVersionUID = 1L;
/*
* (non-Javadoc)
*
* @see java.awt.event.ActionListener#actionPerformed(java.awt.event.ActionEvent)
*/
public void actionPerformed(ActionEvent arg0)
{
openUserData(true);
}
};
exportToHtmlAction = new AbstractAction("Export to html...") {
/**
* nothing to serialize here
*/
private static final long serialVersionUID = 1L;
public void actionPerformed(ActionEvent arg0)
{
File fileToSave = getReportFile();
OTMLToXHTMLConverter otxc =
new OTMLToXHTMLConverter(otViewFactory, bodyPanel.getViewContainer());
otxc.setXHTMLParams(fileToSave, 800, 600);
(new Thread(otxc)).start();
}
};
// Isn't it enabled by default?
exportToHtmlAction.setEnabled(true);
exportCurrentToHtmlAction = new AbstractAction("Export current to html...") {
/**
* nothing to serialize here
*/
private static final long serialVersionUID = 1L;
public void actionPerformed(ActionEvent arg0)
{
try {
File fileToSave = getReportFile();
PageXHTMLExporter otxc =
new PageXHTMLExporter(bodyPanel);
otxc.setXHTMLParams(fileToSave);
(new Thread(otxc)).start();
} catch (Exception e) {
logger.log(Level.SEVERE, "Couldn't get the root object from otrunk", e);
}
}
};
// Isn't it enabled by default?
exportCurrentToHtmlAction.setEnabled(true);
saveUserDataAction = new AbstractAction("Save") {
/**
* Nothing to serialize here
*/
private static final long serialVersionUID = 1L;
/*
* (non-Javadoc)
*
* @see java.awt.event.ActionListener#actionPerformed(java.awt.event.ActionEvent)
*/
public void actionPerformed(ActionEvent arg0)
{
userSession.save();
// the save operation might change the label used by the session
setTitle(baseFrameTitle + ": " + userSession.getLabel());
}
};
saveUserDataAsAction = new AbstractAction("Save As...") {
/**
* nothing to serizile here
*/
private static final long serialVersionUID = 1L;
/*
* (non-Javadoc)
*
* @see java.awt.event.ActionListener#actionPerformed(java.awt.event.ActionEvent)
*/
public void actionPerformed(ActionEvent arg0)
{
if(userSession instanceof OTMLUserSession){
((OTMLUserSession)userSession).setDialogParent(SwingUtilities.getRoot(OTViewer.this));
}
userSession.saveAs();
}
};
loadAction = new AbstractAction("Open Authored Content...") {
/**
* nothing to serizile here
*/
private static final long serialVersionUID = 1L;
/*
* (non-Javadoc)
*
* @see java.awt.event.ActionListener#actionPerformed(java.awt.event.ActionEvent)
*/
public void actionPerformed(ActionEvent arg0)
{
Frame frame = (Frame) SwingUtilities.getRoot(OTViewer.this);
MostRecentFileDialog mrfd =
new MostRecentFileDialog("org.concord.otviewer.openotml");
mrfd.setFilenameFilter("otml");
int retval = mrfd.showOpenDialog(frame);
File file = null;
if (retval == MostRecentFileDialog.APPROVE_OPTION) {
file = mrfd.getSelectedFile();
}
if (file != null && file.exists()) {
logger.info("load file name: " + file);
// if they open an authored file then they are overriding
// the remoteURL,
// at least for now. This makes the title bar update
// correctly, and
// fixes a lockup that happens when they have opened a local
// file and then
// try to save it again.
remoteURL = null;
loadFile(file);
exportToHtmlAction.setEnabled(true);
}
}
};
loadAction.putValue(Action.ACCELERATOR_KEY, KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_O,
java.awt.Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()));
saveAction = new AbstractAction("Save Authored Content...") {
/**
* nothing to serialize here
*/
private static final long serialVersionUID = 1L;
/*
* (non-Javadoc)
*
* @see java.awt.event.ActionListener#actionPerformed(java.awt.event.ActionEvent)
*/
public void actionPerformed(ActionEvent arg0)
{
if (OTConfig.isRemoteSaveData() && remoteURL != null) {
try {
if (OTConfig.isRestEnabled()) {
try {
otrunk.remoteSaveData(xmlDB, remoteURL, OTViewer.HTTP_PUT);
setTitle(remoteURL.toString());
} catch (Exception e) {
otrunk.remoteSaveData(xmlDB, remoteURL, OTViewer.HTTP_POST);
setTitle(remoteURL.toString());
}
} else {
otrunk.remoteSaveData(xmlDB, remoteURL, OTViewer.HTTP_POST);
setTitle(remoteURL.toString());
}
} catch (Exception e) {
JOptionPane.showMessageDialog(
SwingUtilities.getRoot(OTViewer.this),
"There was an error saving. Check your URL and try again.",
"Error Saving", JOptionPane.ERROR_MESSAGE);
e.printStackTrace();
}
} else {
if (currentAuthoredFile == null) {
saveAsAction.actionPerformed(arg0);
return;
}
if (checkForReplace(currentAuthoredFile)) {
try {
ExporterJDOM.export(currentAuthoredFile, xmlDB.getRoot(),
xmlDB);
xmlDB.setDirty(false);
} catch (Exception e) {
handleSavingException(e);
}
}
} // end if (remoteUrl == null)
}
};
saveAction.putValue(Action.ACCELERATOR_KEY, KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_S,
java.awt.Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()));
saveAsAction = new AbstractAction("Save Authored Content As...") {
/**
* nothing to serialize here
*/
private static final long serialVersionUID = 1L;
/*
* (non-Javadoc)
*
* @see java.awt.event.ActionListener#actionPerformed(java.awt.event.ActionEvent)
*/
public void actionPerformed(ActionEvent arg0)
{
Frame frame = (Frame) SwingUtilities.getRoot(OTViewer.this);
MostRecentFileDialog mrfd =
new MostRecentFileDialog("org.concord.otviewer.saveotml");
mrfd.setFilenameFilter("otml");
if (currentAuthoredFile != null) {
mrfd.setCurrentDirectory(currentAuthoredFile.getParentFile());
mrfd.setSelectedFile(currentAuthoredFile);
}
int retval = mrfd.showSaveDialog(frame);
File file = null;
if (retval == MostRecentFileDialog.APPROVE_OPTION) {
file = mrfd.getSelectedFile();
String fileName = file.getPath();
if (!fileName.toLowerCase().endsWith(".otml")) {
file = new File(file.getAbsolutePath() + ".otml");
}
if (checkForReplace(file)) {
try {
ExporterJDOM.export(file, xmlDB.getRoot(), xmlDB);
currentAuthoredFile = file;
currentURL = file.toURL();
xmlDB.setDirty(false);
} catch (Exception e) {
handleSavingException(e);
}
}
frame.setTitle(fileName);
remoteURL = null;
updateMenuBar();
}
}
};
saveRemoteAsAction = new AbstractAction("Save Remotely As...") {
/**
* nothing to serizile here
*/
private static final long serialVersionUID = 1L;
/*
* (non-Javadoc)
*
* @see java.awt.event.ActionListener#actionPerformed(java.awt.event.ActionEvent)
*/
public void actionPerformed(ActionEvent arg0)
{
// Pop up a dialog asking for a URL
// Post the otml to the url
JPanel panel = new JPanel();
panel.setBorder(new EmptyBorder(10, 10, 10, 10));
panel.setLayout(new BorderLayout());
JLabel prompt =
new JLabel("Please enter the URL to which you would like to save:");
prompt.setBorder(new EmptyBorder(0, 0, 10, 0));
JTextField textField = new JTextField();
if (remoteURL == null) {
textField.setText("http:
} else {
textField.setText(remoteURL.toString());
}
JPanel checkboxPanel = new JPanel();
JCheckBox restCheckbox = new JCheckBox("REST Enabled?");
restCheckbox.setSelected(OTConfig.isRestEnabled());
checkboxPanel.setBorder(new EmptyBorder(5, 5, 0, 0));
checkboxPanel.add(restCheckbox);
panel.add(prompt, BorderLayout.NORTH);
panel.add(textField, BorderLayout.CENTER);
panel.add(checkboxPanel, BorderLayout.SOUTH);
int returnVal =
CustomDialog.showOKCancelDialog(
SwingUtilities.getRoot(OTViewer.this), // parent
panel, // custom content
"Save URL", // title
false, // resizeable
true // modal
);
if (returnVal == 0) {
try {
remoteURL = new URL(textField.getText());
System.setProperty(OTConfig.REST_ENABLED_PROP,
Boolean.toString(restCheckbox.isSelected()));
save(OTViewer.HTTP_POST);
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} else {
// CANCELLED
}
}
private void save(String method) {
try {
// WARNING this will cause a security exception if we
// are running in a applet or jnlp which
// has a security sandbox.
otrunk.remoteSaveData(xmlDB, remoteURL, method);
setTitle(remoteURL.toString());
updateMenuBar();
} catch (HTTPRequestException e) {
if (e.getResponseCode() == 405 && ! method.equals(OTViewer.HTTP_PUT)) {
// try again with a PUT since some REST servers don't allow you to POST to an already-created object
save(OTViewer.HTTP_PUT);
} else {
badURL(e);
}
} catch (Exception e) {
badURL(e);
}
}
private void badURL(Exception e) {
logger.log(Level.INFO, "Bad URL. Not saving.", e);
JOptionPane.showMessageDialog(
SwingUtilities.getRoot(OTViewer.this),
"There was an error saving. Check your URL and try again.",
"Error Saving", JOptionPane.ERROR_MESSAGE);
}
};
exportImageAction = new AbstractAction("Export Image...") {
/**
* nothing to serialize here
*/
private static final long serialVersionUID = 1L;
public void actionPerformed(ActionEvent e)
{
// this introduces a dependency on concord Swing project
// instead there needs to be a way to added these actions
// through
// the xml
Component currentComp = bodyPanel.getCurrentComponent();
Util.makeScreenShot(currentComp);
}
};
exportHiResImageAction = new AbstractAction("Export Hi Res Image...") {
/**
* nothing to serialize here
*/
private static final long serialVersionUID = 1L;
public void actionPerformed(ActionEvent e)
{
Component currentComp = bodyPanel.getCurrentComponent();
Util.makeScreenShot(currentComp, 2, 2);
}
};
debugAction = new AbstractAction("Debug Mode") {
/**
* nothing to serialize here
*/
private static final long serialVersionUID = 1L;
public void actionPerformed(ActionEvent e)
{
Object source = e.getSource();
if (((JCheckBoxMenuItem) source).isSelected()) {
System.setProperty(OTConfig.DEBUG_PROP, "true");
} else {
System.setProperty(OTConfig.DEBUG_PROP, "false");
}
try {
reloadWindow();
} catch (Exception exp) {
exp.printStackTrace();
}
SwingUtilities.invokeLater(new Runnable() {
public void run()
{
updateMenuBar();
}
});
exportToHtmlAction.setEnabled(true);
}
};
showConsoleAction = new AbstractAction("Show Console") {
/**
* nothing to serialize here
*/
private static final long serialVersionUID = 1L;
public void actionPerformed(ActionEvent e)
{
if (consoleFrame != null) {
consoleFrame.setVisible(true);
}
}
};
reloadWindowAction = new AbstractAction("Reload window") {
/**
* nothing to serialize here
*/
private static final long serialVersionUID = 1L;
public void actionPerformed(ActionEvent e)
{
try {
reload();
} catch (Exception e1) {
e1.printStackTrace();
}
}
};
reloadWindowAction.putValue(Action.ACCELERATOR_KEY, KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_R,
java.awt.Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()));
exitAction = new ExitAction();
}
public static void main(String[] args) {
System.setProperty("apple.laf.useScreenMenuBar", "true");
createConsoleFrame();
OTViewer viewer = new OTViewer();
if (OTConfig.getBooleanProp(OTConfig.SINGLE_USER_PROP, false)) {
viewer.setUserMode(OTConfig.SINGLE_USER_MODE);
} else if (OTConfig.getBooleanProp(OTConfig.NO_USER_PROP, false)) {
viewer.setUserMode(OTConfig.NO_USER_MODE);
}
viewer.initArgs(args);
}
class ExitAction extends AbstractAction
{
/**
* nothing to serialize here.
*/
private static final long serialVersionUID = 1L;
public ExitAction()
{
super("Exit");
}
public void actionPerformed(ActionEvent e)
{
// If this suceeds then the VM will exit so
// the window will get disposed
exit();
}
}
private void handleSavingException(Exception e)
{
e.printStackTrace();
UserMessageHandler service = otrunk.getService(UserMessageHandler.class);
String title = "Saving Error!";
String message = "There was an error saving!\n";
message += "Please click on the details button and send the text to the developers.\n";
message += "If you were overwritting an existing file, that file should be not have changed.\n";
message += "Any changes made since the last save will be lost when you quit, so if possible\n";
message += "copy and paste your changes into a text editor.\n";
message += "Then restart the application and reload your last saved file.\n";
message += "When quiting the application you'll need to click the 'don't save' button.";
if(service instanceof UserMessageHandlerExt1){
StringWriter sw = new StringWriter();
PrintWriter printStream = new PrintWriter(sw);
e.printStackTrace(printStream);
printStream.close();
((UserMessageHandlerExt1) service).showMessage(message, title, sw.toString());
} else if(service != null){
service.showMessage(message, title);
}
}
} // @jve:decl-index=0:visual-constraint="10,10"
class HtmlFileFilter extends javax.swing.filechooser.FileFilter
{
@Override
public boolean accept(File f)
{
if (f == null)
return false;
if (f.isDirectory())
return true;
return (f.getName().toLowerCase().endsWith(".html"));
}
@Override
public String getDescription()
{
return "HTML files";
}
} // @jve:decl-index=0:visual-constraint="10,10"
|
package org.concord.otrunk.view;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Frame;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Hashtable;
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JCheckBoxMenuItem;
import javax.swing.JComponent;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JSplitPane;
import javax.swing.JTabbedPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.JTree;
import javax.swing.SwingUtilities;
import javax.swing.WindowConstants;
import javax.swing.border.EmptyBorder;
import javax.swing.event.TreeSelectionEvent;
import javax.swing.event.TreeSelectionListener;
import org.concord.applesupport.AppleApplicationAdapter;
import org.concord.applesupport.AppleApplicationUtil;
import org.concord.framework.otrunk.OTChangeEvent;
import org.concord.framework.otrunk.OTChangeListener;
import org.concord.framework.otrunk.OTObject;
import org.concord.framework.otrunk.OTObjectService;
import org.concord.framework.otrunk.OTrunk;
import org.concord.framework.otrunk.view.OTFrameManager;
import org.concord.framework.otrunk.view.OTJComponentServiceFactory;
import org.concord.framework.otrunk.view.OTViewContainer;
import org.concord.framework.otrunk.view.OTViewContainerListener;
import org.concord.framework.otrunk.view.OTViewContext;
import org.concord.framework.otrunk.view.OTViewFactory;
import org.concord.framework.text.UserMessageHandler;
import org.concord.framework.util.SimpleTreeNode;
import org.concord.otrunk.OTMLToXHTMLConverter;
import org.concord.otrunk.OTObjectServiceImpl;
import org.concord.otrunk.OTStateRoot;
import org.concord.otrunk.OTSystem;
import org.concord.otrunk.OTrunkImpl;
import org.concord.otrunk.datamodel.OTDataObject;
import org.concord.otrunk.datamodel.OTDatabase;
import org.concord.otrunk.user.OTUserObject;
import org.concord.otrunk.xml.Exporter;
import org.concord.otrunk.xml.ExporterJDOM;
import org.concord.otrunk.xml.XMLDatabase;
import org.concord.swing.CustomDialog;
import org.concord.swing.MostRecentFileDialog;
import org.concord.swing.StreamRecord;
import org.concord.swing.StreamRecordView;
import org.concord.swing.util.Util;
import org.concord.view.SimpleTreeModel;
import org.concord.view.SwingUserMessageHandler;
/**
* OTViewer Class name and description
*
* Date created: Dec 14, 2004
*
* @author scott
* <p>
*
*/
public class OTViewer extends JFrame
implements TreeSelectionListener, OTViewContainerListener,
AppleApplicationAdapter
{
/**
* first version of this class
*/
private static final long serialVersionUID = 1L;
public final static String TITLE_PROP = "otrunk.view.frame_title";
public final static String HIDE_TREE_PROP = "otrunk.view.hide_tree";
public final static String HTTP_PUT = "PUT";
public final static String HTTP_POST = "POST";
private static OTrunkImpl otrunk;
private static OTViewFactory otViewFactory;
protected int userMode = 0;
OTUserObject currentUser = null;
URL currentURL = null;
String baseFrameTitle = "OTrunk Viewer";
OTViewContainerPanel bodyPanel;
OTFrameManagerImpl frameManager;
JTree folderTreeArea;
SimpleTreeModel folderTreeModel;
JTree dataTreeArea;
SimpleTreeModel dataTreeModel;
JSplitPane splitPane;
JFrame consoleFrame;
// Temp, to close the window
AbstractAction exitAction;
AbstractAction saveAsAction;
JMenuBar menuBar;
XMLDatabase xmlDB;
XMLDatabase userDataDB;
File currentAuthoredFile = null;
File currentUserFile = null;
Hashtable otContainers = new Hashtable();
String startupMessage = "";
boolean justStarted = false;
boolean showTree = false;
URL remoteURL;
private AbstractAction saveUserDataAsAction;
private AbstractAction saveUserDataAction;
private AbstractAction debugAction;
private AbstractAction showConsoleAction;
private AbstractAction newUserDataAction;
private AbstractAction loadUserDataAction;
private AbstractAction loadAction;
private AbstractAction reloadWindowAction;
private AbstractAction saveAction;
private AbstractAction saveRemoteAsAction;
private AbstractAction exportImageAction;
private AbstractAction exportHiResImageAction;
private AbstractAction exportToHtmlAction;
private JDialog commDialog;
/**
* This is true if the user was asked about saving user data after they
* initiated a close of the current view.
*/
private boolean askedAboutSavingUserData = false;
/**
* This is true if the user was asked about saving the user data, and said
* yes
*/
private boolean needToSaveUserData = false;
private boolean useScrollPane;
private OTChangeListener systemChangeListener;
private OTSystem userSystem;
public static void setOTViewFactory(OTViewFactory factory)
{
otViewFactory = factory;
}
public OTViewer(boolean showTree)
{
super();
this.showTree = true;
AppleApplicationUtil.registerWithMacOSX(this);
try {
// this overrides the default base frame title
String title = System.getProperty(TITLE_PROP, null);
if (title != null) {
baseFrameTitle = title;
}
} catch (Throwable t) {
// do nothing, just use the default title
}
setTitle(baseFrameTitle);
setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE);
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e)
{
exitAction.actionPerformed(null);
}
});
consoleFrame = new JFrame("Console");
StreamRecord record = new StreamRecord(10000);
StreamRecordView view = new StreamRecordView(record);
consoleFrame.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
System
.setOut((PrintStream) view.addOutputStream(System.out,
"Console"));
System.setErr((PrintStream) view
.addOutputStream(System.err, System.out));
consoleFrame.getContentPane().add(view);
consoleFrame.setSize(800, 600);
commDialog = new JDialog(this, true);
}
public void setUserMode(int mode)
{
userMode = mode;
}
public void updateTreePane()
{
Dimension minimumSize = new Dimension(100, 50);
folderTreeArea = new JTree(folderTreeModel);
// we are just disabling this however if we want to
// use this tree for authoring, or for managing student
// created objects this will need to be some form of option
folderTreeArea.setEditable(false);
folderTreeArea.addTreeSelectionListener(this);
JComponent leftComponent = null;
JScrollPane folderTreeScrollPane = new JScrollPane(folderTreeArea);
if (System.getProperty(OTViewerHelper.DEBUG_PROP, "").equals("true")) {
// ViewFactory.getComponent(root);
dataTreeArea = new JTree(dataTreeModel);
dataTreeArea.setEditable(false);
dataTreeArea.addTreeSelectionListener(this);
JScrollPane dataTreeScrollPane = new JScrollPane(dataTreeArea);
JTabbedPane tabbedPane = new JTabbedPane();
tabbedPane.add("Folders", folderTreeScrollPane);
tabbedPane.add("Resources", dataTreeScrollPane);
// Provide minimum sizes for the two components in the split pane
folderTreeScrollPane.setMinimumSize(minimumSize);
dataTreeScrollPane.setMinimumSize(minimumSize);
tabbedPane.setMinimumSize(minimumSize);
leftComponent = tabbedPane;
} else {
leftComponent = folderTreeScrollPane;
}
if (splitPane == null) {
splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT,
leftComponent, bodyPanel);
} else {
splitPane.setLeftComponent(leftComponent);
}
splitPane.setOneTouchExpandable(true);
splitPane.setDividerLocation(200);
}
public void initArgs(String[] args)
{
if (args.length > 0) {
String urlStr = null;
if (args[0].equals("-f")) {
if (args.length > 1) {
File inFile = new File(args[1]);
currentAuthoredFile = inFile;
try {
URL url = inFile.toURL();
urlStr = url.toString();
} catch (Exception e) {
e.printStackTrace();
urlStr = null;
}
}
} else if (args[0].equals("-r")) {
if (args.length > 1) {
ClassLoader cl = OTViewer.class.getClassLoader();
URL url = cl.getResource(args[1]);
urlStr = url.toString();
}
} else {
urlStr = args[0];
}
initWithWizard(urlStr);
} else {
initWithWizard(null);
}
}
public void init(String url)
{
updateRemoteURL(url);
createActions();
updateMenuBar();
setJMenuBar(menuBar);
frameManager = new OTFrameManagerImpl();
bodyPanel = new OTViewContainerPanel(frameManager);
bodyPanel.addViewContainerListener(this);
if (showTree) {
dataTreeModel = new SimpleTreeModel();
folderTreeModel = new SimpleTreeModel();
updateTreePane();
getContentPane().add(splitPane);
} else {
getContentPane().add(bodyPanel);
}
SwingUtilities.invokeLater(new Runnable() {
public void run()
{
Dimension screenSize = Toolkit.getDefaultToolkit()
.getScreenSize();
if (screenSize.width < 1000 || screenSize.height < 700) {
setVisible(true);
int state = getExtendedState();
// Set the maximized bits
state |= Frame.MAXIMIZED_BOTH;
// Maximize the frame
setExtendedState(state);
} else {
int cornerX = 100;
int cornerY = 100;
int sizeX = 725;
int sizeY = 500;
// OTViewService viewService = otViewFactory.
setBounds(cornerX, cornerY, cornerX + sizeX, cornerY
+ sizeY);
setVisible(true);
}
}
});
if (url == null) {
return;
}
try {
initializeURL(new URL(url));
} catch (MalformedURLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (Exception e) {
// FIXME: this should popup a dialog
System.err.println("Can't load url");
e.printStackTrace();
return;
}
}
public void initializeURL(URL url) throws Exception
{
loadURL(url);
OTMainFrame mainFrame = (OTMainFrame) otrunk
.getService(OTMainFrame.class);
if (!mainFrame.getShowLeftPanel()) {
splitPane.getLeftComponent().setVisible(false);
}
useScrollPane = true;
if (mainFrame.getFrame() != null) {
if (mainFrame.getFrame().isResourceSet("width")
&& mainFrame.getFrame().isResourceSet("height")) {
int cornerX = 100;
int cornerY = 100;
int sizeX = mainFrame.getFrame().getWidth();
int sizeY = mainFrame.getFrame().getHeight();
setBounds(cornerX, cornerY, cornerX + sizeX, cornerY
+ sizeY);
repaint();
}
useScrollPane = mainFrame.getFrame().getUseScrollPane();
}
bodyPanel.setUseScrollPane(useScrollPane);
setupBodyPanel();
}
public void initWithWizard(String url)
{
justStarted = true;
init(url);
if (userMode == OTViewerHelper.SINGLE_USER_MODE) {
SwingUtilities.invokeLater(new Runnable() {
public void run()
{
instructionPanel();
}
});
}
}
public void loadUserDataFile(File file)
{
currentUserFile = file;
try {
loadUserDataURL(file.toURL(), file.getName());
} catch (Exception e) {
e.printStackTrace();
}
}
public void loadUserDataURL(URL url, String name)
throws Exception
{
XMLDatabase db = new XMLDatabase(url);
db.loadObjects();
loadUserDataDb(db, name);
}
public void loadUserDataDb(XMLDatabase db, String name)
throws Exception
{
userDataDB = db;
currentUser = otrunk.registerUserDataDatabase(userDataDB, name);
reloadWindow();
}
public void reloadOverlays()
{
try {
otrunk.reloadOverlays(currentUser, userDataDB);
reloadWindow();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private void loadFile(File file)
{
currentAuthoredFile = file;
try {
initializeURL(currentAuthoredFile.toURL());
} catch (Exception e) {
e.printStackTrace();
}
}
private void loadURL(URL url)
throws Exception
{
try {
xmlDB = new XMLDatabase(url, System.err);
if (Boolean.getBoolean(OTViewerHelper.AUTHOR_PROP)) {
xmlDB.setTrackResourceInfo(true);
}
xmlDB.loadObjects();
} catch (org.jdom.input.JDOMParseException e) {
String xmlWarningTitle = "XML Decoding error";
String xmlWarningMessage = "There appears to a problem parsing the XML of this document. \n"
+ "Please show this error message to one of the workshop leaders. \n\n"
+ e.getMessage();
JOptionPane.showMessageDialog(null, xmlWarningMessage,
xmlWarningTitle, JOptionPane.ERROR_MESSAGE);
throw e;
}
otrunk = new OTrunkImpl(xmlDB,
new Object[] { new SwingUserMessageHandler(this) },
new Class[] { UserMessageHandler.class });
OTViewFactory myViewFactory = (OTViewFactory) otrunk
.getService(OTViewFactory.class);
if (myViewFactory != null) {
otViewFactory = myViewFactory;
}
OTViewContext factoryContext = otViewFactory.getViewContext();
factoryContext.addViewService(OTrunk.class, otrunk);
factoryContext.addViewService(OTFrameManager.class, frameManager);
factoryContext.addViewService(OTJComponentServiceFactory.class,
new OTJComponentServiceFactoryImpl());
currentURL = url;
}
// This method was refactored out of loadURL
private void setupBodyPanel()
throws Exception
{
bodyPanel.setTopLevelContainer(true);
bodyPanel.setOTViewFactory(otViewFactory);
// set the current mode from the viewservice to the main bodyPanel
bodyPanel.setViewMode(otViewFactory.getDefaultMode());
// set the viewFactory of the frame manager
frameManager.setViewFactory(otViewFactory);
xmlDB.setDirty(false);
reloadWindow();
}
private void reloadWindow()
throws Exception
{
OTObject root = null;
boolean overrideShowTree = false;
switch (userMode) {
case OTViewerHelper.NO_USER_MODE:
root = otrunk.getRoot();
break;
case OTViewerHelper.SINGLE_USER_MODE:
if (userDataDB == null) {
// FIXME This is an error
// the newAnonUserData should have been called before this
// method is
// called
// no user file has been started yet
overrideShowTree = true;
root = null;
} else {
OTObject otRoot = otrunk.getRoot();
root = otrunk.getUserRuntimeObject(otRoot, currentUser);
OTObject realRoot = otrunk.getRealRoot();
if (realRoot instanceof OTSystem) {
OTSystem localUserSystem = (OTSystem) otrunk
.getUserRuntimeObject(realRoot, currentUser);
// FIXME there should be a better way than this because we
// have to handle
// multiple users.
if (localUserSystem != userSystem) {
userSystem = localUserSystem;
systemChangeListener = new OTChangeListener() {
public void stateChanged(OTChangeEvent e)
{
if ("overlays".equals(e.getProperty())) {
reloadOverlays();
}
}
};
userSystem.addOTChangeListener(systemChangeListener);
}
}
}
}
if (showTree && !overrideShowTree) {
OTDataObject rootDataObject = xmlDB.getRoot();
dataTreeModel.setRoot(new OTDataObjectNode("root", rootDataObject,
otrunk));
folderTreeModel.setRoot(new OTFolderNode(root));
}
bodyPanel.setCurrentObject(root);
if (showTree && !overrideShowTree) {
folderTreeModel
.fireTreeStructureChanged((SimpleTreeNode) folderTreeModel
.getRoot());
dataTreeModel
.fireTreeStructureChanged((SimpleTreeNode) dataTreeModel
.getRoot());
}
Frame frame = (Frame) SwingUtilities.getRoot(this);
switch (userMode) {
case OTViewerHelper.NO_USER_MODE:
if (remoteURL != null) {
frame.setTitle(baseFrameTitle + ": " + remoteURL.toString());
} else {
frame.setTitle(baseFrameTitle + ": " + currentURL.toString());
}
break;
case OTViewerHelper.SINGLE_USER_MODE:
if (currentUserFile != null) {
frame.setTitle(baseFrameTitle + ": "
+ currentUserFile.toString());
} else if (System.getProperty(TITLE_PROP, null) != null) {
frame.setTitle(baseFrameTitle);
} else if (userDataDB != null) {
frame.setTitle(baseFrameTitle + ": Untitled");
} else {
frame.setTitle(baseFrameTitle);
}
break;
}
saveUserDataAction.setEnabled(userDataDB != null);
saveUserDataAsAction.setEnabled(userDataDB != null);
}
public void reload()
throws Exception
{
initializeURL(currentURL);
}
public OTDatabase getUserDataDb()
{
return userDataDB;
}
/**
* You should call reloadWindow after calling this method to make sure the
* display reflects this change
*
* @param userObject
*/
public void setCurrentUser(OTUserObject userObject)
{
currentUser = userObject;
}
public static void main(String[] args)
{
System.setProperty("apple.laf.useScreenMenuBar", "true");
OTViewer viewer = new OTViewer(!Boolean.getBoolean(HIDE_TREE_PROP));
if (Boolean.getBoolean(OTViewerHelper.SINGLE_USER_PROP)) {
viewer.setUserMode(OTViewerHelper.SINGLE_USER_MODE);
} else if (Boolean.getBoolean(OTViewerHelper.NO_USER_PROP)) {
viewer.setUserMode(OTViewerHelper.NO_USER_MODE);
}
viewer.initArgs(args);
}
class ExitAction extends AbstractAction
{
/**
* nothing to serialize here.
*/
private static final long serialVersionUID = 1L;
public ExitAction()
{
super("Exit");
}
public void actionPerformed(ActionEvent e)
{
// If this suceeds then the VM will exit so
// the window will get disposed
exit();
}
}
/*
* (non-Javadoc)
*
* @see org.concord.otrunk.view.OTViewContainerListener#currentObjectChanged(org.concord.framework.otrunk.view.OTViewContainer)
*/
public void currentObjectChanged(OTViewContainer container)
{
final OTViewContainer myContainer = container;
// TODO Auto-generated method stub
SwingUtilities.invokeLater(new Runnable() {
public void run()
{
OTObject currentObject = myContainer.getCurrentObject();
if (folderTreeArea != null) {
OTFolderNode node = (OTFolderNode) folderTreeArea
.getLastSelectedPathComponent();
if (node == null)
return;
if (node.getPfObject() != currentObject) {
folderTreeArea.setSelectionPath(null);
}
}
}
});
}
/*
* (non-Javadoc)
*
* @see javax.swing.event.TreeSelectionListener#valueChanged(javax.swing.event.TreeSelectionEvent)
*/
public void valueChanged(TreeSelectionEvent event)
{
if (event.getSource() == folderTreeArea) {
OTFolderNode node = (OTFolderNode) folderTreeArea
.getLastSelectedPathComponent();
if (node == null)
return;
OTObject pfObject = node.getPfObject();
bodyPanel.setCurrentObject(pfObject);
if (splitPane.getRightComponent() != bodyPanel) {
splitPane.setRightComponent(bodyPanel);
}
} else if (event.getSource() == dataTreeArea) {
SimpleTreeNode node = (SimpleTreeNode) dataTreeArea
.getLastSelectedPathComponent();
Object resourceValue = null;
if (node != null) {
resourceValue = node.getObject();
if (resourceValue == null) {
resourceValue = "null resource value";
}
} else {
resourceValue = "no selected data object";
}
JComponent nodeView = null;
if (resourceValue instanceof OTDataObject) {
nodeView = new OTDataObjectView((OTDataObject) resourceValue);
} else {
nodeView = new JTextArea(resourceValue.toString());
}
JScrollPane scrollPane = new JScrollPane(nodeView);
splitPane.setRightComponent(scrollPane);
}
}
private void updateRemoteURL(String defaultURL)
{
String remote = System
.getProperty(OTViewerHelper.REMOTE_URL_PROP, null);
try {
if (remote == null) {
if (defaultURL.startsWith("http:")) {
remoteURL = new URL(defaultURL);
}
} else {
remoteURL = new URL(remote);
}
} catch (Exception e) {
remoteURL = null;
System.err.println("Remote URL is invalid.");
e.printStackTrace();
}
}
public void remoteSaveData(String method)
throws Exception
{
HttpURLConnection urlConn;
DataOutputStream urlDataOut;
BufferedReader urlDataIn;
// If method isn't "POST" or "PUT", throw an exception
if (!(method.compareTo(OTViewer.HTTP_POST) == 0 || method
.compareTo(OTViewer.HTTP_PUT) == 0)) {
throw new Exception("Invalid HTTP Request method for data saving");
}
urlConn = (HttpURLConnection) remoteURL.openConnection();
urlConn.setDoInput(true);
urlConn.setDoOutput(true);
urlConn.setUseCaches(false);
urlConn.setRequestMethod(method);
urlConn.setRequestProperty("Content-Type", "application/xml");
// Send POST output.
urlDataOut = new DataOutputStream(urlConn.getOutputStream());
Exporter.export(urlDataOut, xmlDB.getRoot(), xmlDB);
urlDataOut.flush();
urlDataOut.close();
// Get response data.
urlDataIn = new BufferedReader(new InputStreamReader(
new DataInputStream(urlConn.getInputStream())));
String str;
String response = "";
while (null != ((str = urlDataIn.readLine()))) {
response += str + "\n";
}
urlDataIn.close();
// Need to trap non-HTTP 200/300 responses and throw an exception (if an
// exception isn't thrown already) and capture the exceptions upstream
int code = urlConn.getResponseCode();
if (code >= 400) {
throw new Exception("HTTP Response: "
+ urlConn.getResponseMessage() + "\n\n" + response);
}
urlConn.disconnect();
xmlDB.setDirty(false);
setTitle(remoteURL.toString());
}
public void createActions()
{
newUserDataAction = new AbstractAction("New") {
/**
* nothing to serialize here
*/
private static final long serialVersionUID = 1L;
/*
* (non-Javadoc)
*
* @see java.awt.event.ActionListener#actionPerformed(java.awt.event.ActionEvent)
*/
public void actionPerformed(ActionEvent arg0)
{
createNewUser();
}
};
loadUserDataAction = new AbstractAction("Open...") {
/**
* nothing to serialize here. Just the parent class.
*/
private static final long serialVersionUID = 1L;
/*
* (non-Javadoc)
*
* @see java.awt.event.ActionListener#actionPerformed(java.awt.event.ActionEvent)
*/
public void actionPerformed(ActionEvent arg0)
{
openUserData();
}
};
exportToHtmlAction = new AbstractAction("Export to html...") {
/**
* nothing to serialize here
*/
private static final long serialVersionUID = 1L;
public void actionPerformed(ActionEvent arg0)
{
File fileToSave = getReportFile();
OTMLToXHTMLConverter otxc = new OTMLToXHTMLConverter(
otViewFactory, bodyPanel.getViewContainer());
otxc.setXHTMLParams(fileToSave, 800, 600);
(new Thread(otxc)).start();
}
};
// Isn't it enabled by default?
exportToHtmlAction.setEnabled(true);
saveUserDataAction = new AbstractAction("Save") {
/**
* Nothing to serialize here
*/
private static final long serialVersionUID = 1L;
/*
* (non-Javadoc)
*
* @see java.awt.event.ActionListener#actionPerformed(java.awt.event.ActionEvent)
*/
public void actionPerformed(ActionEvent arg0)
{
if (currentUserFile == null || !currentUserFile.exists()) {
saveUserDataAsAction.actionPerformed(arg0);
return;
}
if (currentUserFile.exists()) {
try {
Exporter.export(currentUserFile, userDataDB.getRoot(),
userDataDB);
userDataDB.setDirty(false);
} catch (Exception e) {
e.printStackTrace();
}
}
}
};
saveUserDataAsAction = new AbstractAction("Save As...") {
/**
* nothing to serizile here
*/
private static final long serialVersionUID = 1L;
/*
* (non-Javadoc)
*
* @see java.awt.event.ActionListener#actionPerformed(java.awt.event.ActionEvent)
*/
public void actionPerformed(ActionEvent arg0)
{
Frame frame = (Frame) SwingUtilities.getRoot(OTViewer.this);
MostRecentFileDialog mrfd = new MostRecentFileDialog(
"org.concord.otviewer.saveotml");
mrfd.setFilenameFilter("otml");
if (currentUserFile != null) {
mrfd.setCurrentDirectory(currentUserFile.getParentFile());
mrfd.setSelectedFile(currentUserFile);
}
int retval = mrfd.showSaveDialog(frame);
File file = null;
if (retval == MostRecentFileDialog.APPROVE_OPTION) {
file = mrfd.getSelectedFile();
String fileName = file.getPath();
currentUserFile = file;
if (!fileName.toLowerCase().endsWith(".otml")) {
currentUserFile = new File(currentUserFile
.getAbsolutePath()
+ ".otml");
}
try {
Exporter.export(currentUserFile, userDataDB.getRoot(),
userDataDB);
userDataDB.setDirty(false);
setTitle(baseFrameTitle + ": "
+ currentUserFile.toString());
} catch (Exception e) {
e.printStackTrace();
}
frame.setTitle(fileName);
}
}
};
loadAction = new AbstractAction("Open Authored Content...") {
/**
* nothing to serizile here
*/
private static final long serialVersionUID = 1L;
/*
* (non-Javadoc)
*
* @see java.awt.event.ActionListener#actionPerformed(java.awt.event.ActionEvent)
*/
public void actionPerformed(ActionEvent arg0)
{
Frame frame = (Frame) SwingUtilities.getRoot(OTViewer.this);
MostRecentFileDialog mrfd = new MostRecentFileDialog(
"org.concord.otviewer.openotml");
mrfd.setFilenameFilter("otml");
int retval = mrfd.showOpenDialog(frame);
File file = null;
if (retval == MostRecentFileDialog.APPROVE_OPTION) {
file = mrfd.getSelectedFile();
}
if (file != null && file.exists()) {
System.out.println("load file name: " + file);
loadFile(file);
exportToHtmlAction.setEnabled(true);
}
}
};
saveAction = new AbstractAction("Save Authored Content...") {
/**
* nothing to serizile here
*/
private static final long serialVersionUID = 1L;
/*
* (non-Javadoc)
*
* @see java.awt.event.ActionListener#actionPerformed(java.awt.event.ActionEvent)
*/
public void actionPerformed(ActionEvent arg0)
{
if (remoteURL != null) {
try {
if (Boolean
.getBoolean(OTViewerHelper.REST_ENABLED_PROP)) {
try {
remoteSaveData(OTViewer.HTTP_PUT);
} catch (Exception e) {
remoteSaveData(OTViewer.HTTP_POST);
}
} else {
remoteSaveData(OTViewer.HTTP_POST);
}
} catch (Exception e) {
JOptionPane
.showMessageDialog(
(Frame) SwingUtilities
.getRoot(OTViewer.this),
"There was an error saving. Check your URL and try again.",
"Error Saving",
JOptionPane.ERROR_MESSAGE);
e.printStackTrace();
}
} else {
if (currentAuthoredFile == null) {
saveAsAction.actionPerformed(arg0);
return;
}
if (checkForReplace(currentAuthoredFile)) {
try {
ExporterJDOM.export(currentAuthoredFile, xmlDB
.getRoot(), xmlDB);
xmlDB.setDirty(false);
} catch (Exception e) {
e.printStackTrace();
}
}
} // end if (remoteUrl == null)
}
};
saveAsAction = new AbstractAction("Save Authored Content As...") {
/**
* nothing to serizile here
*/
private static final long serialVersionUID = 1L;
/*
* (non-Javadoc)
*
* @see java.awt.event.ActionListener#actionPerformed(java.awt.event.ActionEvent)
*/
public void actionPerformed(ActionEvent arg0)
{
Frame frame = (Frame) SwingUtilities.getRoot(OTViewer.this);
MostRecentFileDialog mrfd = new MostRecentFileDialog(
"org.concord.otviewer.saveotml");
mrfd.setFilenameFilter("otml");
if (currentAuthoredFile != null) {
mrfd.setCurrentDirectory(currentAuthoredFile
.getParentFile());
mrfd.setSelectedFile(currentAuthoredFile);
}
int retval = mrfd.showSaveDialog(frame);
File file = null;
if (retval == MostRecentFileDialog.APPROVE_OPTION) {
file = mrfd.getSelectedFile();
String fileName = file.getPath();
if (!fileName.toLowerCase().endsWith(".otml")) {
file = new File(file.getAbsolutePath() + ".otml");
}
if (checkForReplace(file)) {
try {
ExporterJDOM.export(file, xmlDB.getRoot(), xmlDB);
currentAuthoredFile = file;
xmlDB.setDirty(false);
} catch (Exception e) {
e.printStackTrace();
}
}
frame.setTitle(fileName);
remoteURL = null;
updateMenuBar();
}
}
};
saveRemoteAsAction = new AbstractAction("Save Remotely As...") {
/**
* nothing to serizile here
*/
private static final long serialVersionUID = 1L;
/*
* (non-Javadoc)
*
* @see java.awt.event.ActionListener#actionPerformed(java.awt.event.ActionEvent)
*/
public void actionPerformed(ActionEvent arg0)
{
// Pop up a dialog asking for a URL
// Post the otml to the url
JPanel panel = new JPanel();
panel.setBorder(new EmptyBorder(10, 10, 10, 10));
panel.setLayout(new BorderLayout());
JLabel prompt = new JLabel(
"Please enter the URL to which you would like to save:");
prompt.setBorder(new EmptyBorder(0, 0, 10, 0));
JTextField textField = new JTextField();
if (remoteURL == null) {
textField.setText("http:
} else {
textField.setText(remoteURL.toString());
}
JPanel checkboxPanel = new JPanel();
JCheckBox restCheckbox = new JCheckBox("REST Enabled?");
restCheckbox.setSelected(Boolean
.getBoolean(OTViewerHelper.REST_ENABLED_PROP));
checkboxPanel.setBorder(new EmptyBorder(5, 5, 0, 0));
checkboxPanel.add(restCheckbox);
panel.add(prompt, BorderLayout.NORTH);
panel.add(textField, BorderLayout.CENTER);
panel.add(checkboxPanel, BorderLayout.SOUTH);
int returnVal = CustomDialog.showOKCancelDialog(
(Frame) SwingUtilities.getRoot(OTViewer.this), // parent
panel, // custom content
"Save URL", // title
false, // resizeable
true // modal
);
if (returnVal == 0) {
try {
remoteURL = new URL(textField.getText());
System.setProperty(OTViewerHelper.REST_ENABLED_PROP,
Boolean.toString(restCheckbox.isSelected()));
remoteSaveData(OTViewer.HTTP_POST);
updateMenuBar();
} catch (Exception e) {
System.err.println("Bad URL. Not saving.");
JOptionPane
.showMessageDialog(
(Frame) SwingUtilities
.getRoot(OTViewer.this),
"There was an error saving. Check your URL and try again.",
"Error Saving",
JOptionPane.ERROR_MESSAGE);
e.printStackTrace();
}
} else {
// CANCELLED
}
}
};
exportImageAction = new AbstractAction("Export Image...") {
/**
* nothing to serialize here
*/
private static final long serialVersionUID = 1L;
public void actionPerformed(ActionEvent e)
{
// this introduces a dependency on concord Swing project
// instead there needs to be a way to added these actions
// through
// the xml
Component currentComp = bodyPanel.getCurrentComponent();
Util.makeScreenShot(currentComp);
}
};
exportHiResImageAction = new AbstractAction("Export Hi Res Image...") {
/**
* nothing to serizile here
*/
private static final long serialVersionUID = 1L;
public void actionPerformed(ActionEvent e)
{
Component currentComp = bodyPanel.getCurrentComponent();
Util.makeScreenShot(currentComp, 2, 2);
}
};
debugAction = new AbstractAction("Debug Mode") {
/**
* nothing to serizile here
*/
private static final long serialVersionUID = 1L;
public void actionPerformed(ActionEvent e)
{
Object source = e.getSource();
if (((JCheckBoxMenuItem) source).isSelected()) {
System.setProperty(OTViewerHelper.DEBUG_PROP, "true");
} else {
System.setProperty(OTViewerHelper.DEBUG_PROP, "false");
}
try {
reloadWindow();
} catch (Exception exp) {
exp.printStackTrace();
}
SwingUtilities.invokeLater(new Runnable() {
public void run()
{
updateMenuBar();
}
});
exportToHtmlAction.setEnabled(true);
}
};
showConsoleAction = new AbstractAction("Show Console") {
/**
* nothing to serialize here
*/
private static final long serialVersionUID = 1L;
public void actionPerformed(ActionEvent e)
{
if (consoleFrame != null) {
consoleFrame.setVisible(true);
}
}
};
reloadWindowAction = new AbstractAction("Reload window") {
/**
* nothing to serialize here
*/
private static final long serialVersionUID = 1L;
public void actionPerformed(ActionEvent e)
{
try {
reload();
} catch (Exception e1) {
e1.printStackTrace();
}
}
};
exitAction = new ExitAction();
}
/**
* @return Returns the menuBar.
*/
public JMenuBar updateMenuBar()
{
JMenu fileMenu = null;
if (menuBar == null) {
menuBar = new JMenuBar();
fileMenu = new JMenu("File");
menuBar.add(fileMenu);
} else {
fileMenu = menuBar.getMenu(0);
fileMenu.removeAll();
}
if (Boolean.getBoolean(OTViewerHelper.AUTHOR_PROP)) {
userMode = OTViewerHelper.NO_USER_MODE;
}
if (userMode == OTViewerHelper.SINGLE_USER_MODE) {
fileMenu.setEnabled(!justStarted);
fileMenu.add(newUserDataAction);
fileMenu.add(loadUserDataAction);
fileMenu.add(saveUserDataAction);
fileMenu.add(saveUserDataAsAction);
}
if (Boolean.getBoolean(OTViewerHelper.DEBUG_PROP)) {
if (userMode == OTViewerHelper.SINGLE_USER_MODE) {
loadAction.putValue(Action.NAME, "Open Authored Content...");
saveAction.putValue(Action.NAME, "Save Authored Content");
saveAsAction.putValue(Action.NAME,
"Save Authored Content As...");
saveRemoteAsAction.putValue(Action.NAME,
"Save Authored Content Remotely As...");
} else {
loadAction.putValue(Action.NAME, "Open...");
saveAction.putValue(Action.NAME, "Save");
saveAsAction.putValue(Action.NAME, "Save As...");
saveRemoteAsAction.putValue(Action.NAME, "Save Remotely As...");
}
fileMenu.add(loadAction);
fileMenu.add(saveAction);
fileMenu.add(saveAsAction);
fileMenu.add(saveRemoteAsAction);
}
if (Boolean.getBoolean(OTViewerHelper.AUTHOR_PROP)
&& !Boolean.getBoolean(OTViewerHelper.DEBUG_PROP)) {
if (userMode == OTViewerHelper.SINGLE_USER_MODE) {
loadAction.putValue(Action.NAME, "Open Authored Content...");
saveAction.putValue(Action.NAME, "Save Authored Content");
saveAsAction.putValue(Action.NAME,
"Save Authored Content As...");
} else {
loadAction.putValue(Action.NAME, "Open...");
saveAction.putValue(Action.NAME, "Save");
saveAsAction.putValue(Action.NAME, "Save As...");
}
fileMenu.add(loadAction);
fileMenu.add(saveAction);
fileMenu.add(saveAsAction);
}
if (Boolean.getBoolean("otrunk.view.export_image")) {
fileMenu.add(exportImageAction);
fileMenu.add(exportHiResImageAction);
}
fileMenu.add(exportToHtmlAction);
fileMenu.add(showConsoleAction);
if (Boolean.getBoolean(OTViewerHelper.AUTHOR_PROP)
|| Boolean.getBoolean(OTViewerHelper.DEBUG_PROP)) {
fileMenu.add(reloadWindowAction);
}
JCheckBoxMenuItem debugItem = new JCheckBoxMenuItem(debugAction);
debugItem.setSelected(Boolean.getBoolean(OTViewerHelper.DEBUG_PROP));
fileMenu.add(debugItem);
fileMenu.add(exitAction);
return menuBar;
}
boolean checkForReplace(File file)
{
if (file == null){
return false;
}
if (!file.exists()) {
return true; // File doesn't exist, so go ahead and save
}
if (currentAuthoredFile != null && file.compareTo(currentAuthoredFile) == 0){
return true; // we're already authoring this file, so no need to
// prompt
}
final Object[] options = { "Yes", "No" };
return javax.swing.JOptionPane.showOptionDialog(null, "The file '"
+ file.getName() + "' already exists. "
+ "Replace existing file?", "Warning",
javax.swing.JOptionPane.YES_NO_OPTION,
javax.swing.JOptionPane.WARNING_MESSAGE, null, options,
options[1]) == javax.swing.JOptionPane.YES_OPTION;
}
/**
* Checks if the user has unsaved work. If they do then it prompts them to
* confirm what they are doing. If they cancel then it returns false.
*
* @return
*/
public boolean checkForUnsavedUserData()
{
if (currentUser != null && userDataDB != null) {
if (userDataDB.isDirty()) {
// show dialog message telling them they haven't
// saved their work
// FIXME
String options[] = { "Don't Save", "Cancel", "Save" };
askedAboutSavingUserData = true;
int chosenOption = JOptionPane.showOptionDialog(this,
"Save Changes?", "Save Changes?",
JOptionPane.DEFAULT_OPTION,
JOptionPane.WARNING_MESSAGE, null, options, options[2]);
switch (chosenOption) {
case 0:
System.err.println("Not saving work");
break;
case 1:
System.err.println("Canceling close");
return false;
case 2:
System.err.println("Set needToSaveUserData true");
needToSaveUserData = true;
break;
}
}
}
return true;
}
/**
* Checks if the user has unsaved authored data. If they do then it prompts
* them to confirm what they are doing. If they cancel then it returns
* false.
*
* @return
*/
public boolean checkForUnsavedAuthorData()
{
if (xmlDB != null) {
if (xmlDB.isDirty()) {
// show dialog message telling them they haven't
// saved their work
// FIXME
String options[] = { "Don't Save", "Cancel", "Save" };
int chosenOption = JOptionPane.showOptionDialog(this,
"Save Changes?", "Save Changes?",
JOptionPane.DEFAULT_OPTION,
JOptionPane.WARNING_MESSAGE, null, options, options[2]);
switch (chosenOption) {
case 0:
System.err.println("Not saving authored data");
break;
case 1:
System.err.println("Canceling close");
return false;
case 2:
System.err.println("Saving authored data");
saveAction.actionPerformed(null);
break;
}
}
}
return true;
}
/**
* This does not check for unsaved user data
*
*/
public void newAnonUserData()
{
// call some new method for creating a new un-saved user state
// this should set the currentUserFile to null, so the save check
// prompts
// for a file name
try {
// need to make a brand new stateDB
userDataDB = new XMLDatabase();
// System.out.println("otrunk: " + otrunk + " userDatabase: " +
// userDataDB);
OTObjectService objService = otrunk.createObjectService(userDataDB);
OTStateRoot stateRoot = (OTStateRoot) objService
.createObject(OTStateRoot.class);
userDataDB.setRoot(stateRoot.getGlobalId());
stateRoot.setFormatVersionString("1.0");
OTUserObject userObject = OTViewerHelper.createUser(
"anon_single_user", objService);
otrunk.initUserObjectService((OTObjectServiceImpl) objService,
userObject, stateRoot);
userDataDB.setDirty(false);
currentUserFile = null;
setCurrentUser(userObject);
reloadWindow();
} catch (Exception e) {
e.printStackTrace();
}
}
public boolean exit()
{
try {
if (!checkForUnsavedUserData()) {
// the user canceled the operation
return false;
}
if (Boolean.getBoolean(OTViewerHelper.AUTHOR_PROP)
&& !checkForUnsavedAuthorData()) {
// the user canceled the operation
return false;
}
// FIXME there is a problem with this logic. If the user saved data
// just before closing
// checkForUnsavedUserData will not see any unsaved data. But if
// some view creates
// data in the viewClosed method then that data will not get saved
// here.
// I think the key to solving this is to seperate the
// automatic/logging data from the
// user visible data. And then make a rule that saving data in the
// viewClosed method
// is not allowed.
bodyPanel.setCurrentObject(null);
conditionalSaveUserData();
if (otrunk != null)
otrunk.close();
} catch (Exception exp) {
exp.printStackTrace();
// exit anyhow
}
System.exit(0);
return true;
}
protected void conditionalSaveUserData()
{
if (!askedAboutSavingUserData) {
checkForUnsavedUserData();
}
if (needToSaveUserData) {
saveUserDataAction.actionPerformed(null);
} else {
System.err.println("Not saving work before closing.");
}
// Reset these back to false, so if the user is switching to a new
// user or loading a new file we are in a clean state, for that file or
// user
askedAboutSavingUserData = false;
needToSaveUserData = false;
}
public File getReportFile()
{
Frame frame = (Frame) SwingUtilities.getRoot(OTViewer.this);
MostRecentFileDialog mrfd = new MostRecentFileDialog(
"org.concord.otviewer.saveotml");
mrfd.setFilenameFilter("html");
if (currentUserFile != null) {
mrfd.setCurrentDirectory(currentUserFile.getParentFile());
}
int retval = mrfd.showSaveDialog(frame);
File file = null;
if (retval == MostRecentFileDialog.APPROVE_OPTION) {
file = mrfd.getSelectedFile();
String fileName = file.getPath();
if (!fileName.toLowerCase().endsWith(".html")) {
file = new File(file.getAbsolutePath() + ".html");
}
return file;
}
return null;
}
public void createNewUser()
{
if (!checkForUnsavedUserData()) {
// the user canceled the operation
return;
}
// This ensures viewClosed is called
bodyPanel.setCurrentObject(null);
conditionalSaveUserData();
// call some new method for creating a new un-saved user state
// this should set the currentUserFile to null, so the save check
// prompts
// for a file name
newAnonUserData();
exportToHtmlAction.setEnabled(true);
}
public void openUserData()
{
if (!checkForUnsavedUserData()) {
// the user canceled the operation
return;
}
// FIXME Calling the method below would insure the view is closed, and
// that any data that is
// is modified in that view closed operation will get saved, however if
// the user
// cancels the open dialog then we would be left in an unknown
// state. The current view would be closed which they would want to see
// again.
// bodyPanel.setCurrentObject(null);
conditionalSaveUserData();
Frame frame = (Frame) SwingUtilities.getRoot(OTViewer.this);
MostRecentFileDialog mrfd = new MostRecentFileDialog(
"org.concord.otviewer.openotml");
mrfd.setFilenameFilter("otml");
int retval = mrfd.showOpenDialog(frame);
File file = null;
if (retval == MostRecentFileDialog.APPROVE_OPTION) {
file = mrfd.getSelectedFile();
}
if (file != null && file.exists()) {
loadUserDataFile(file);
exportToHtmlAction.setEnabled(true);
}
}
public void instructionPanel()
{
commDialog.setResizable(false);
JPanel panel = new JPanel();
panel.setBackground(Color.WHITE);
panel.setLayout(null);
JLabel lNew = new JLabel(
"Click the \"New\" button to create a new portfolio:");
JLabel lOpen = new JLabel(
"Click the \"Open\" button to open a saved portfolio:");
JButton bNew = new JButton("New");
JButton bOpen = new JButton("Open");
panel.add(lNew);
panel.add(lOpen);
panel.add(bNew);
panel.add(bOpen);
lNew.setLocation(50, 100);
lOpen.setLocation(50, 150);
bNew.setLocation(400, 100);
bOpen.setLocation(400, 150);
lNew.setSize(340, 30);
lOpen.setSize(340, 30);
bNew.setSize(70, 25);
bOpen.setSize(70, 25);
bNew.setOpaque(false);
bOpen.setOpaque(false);
bNew.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
commDialog.setVisible(false);
createNewUser();
}
});
bOpen.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
commDialog.setVisible(false);
openUserData();
}
});
commDialog.getContentPane().add(panel);
commDialog.setBounds(200, 200, 500, 300);
SwingUtilities.invokeLater(new Runnable() {
public void run()
{
commDialog.setVisible(true);
justStarted = false;
updateMenuBar();
}
});
}
public OTViewContainerPanel getViewContainerPanel()
{
return this.bodyPanel;
}
public void setExitAction(AbstractAction exitAction)
{
this.exitAction = exitAction;
}
/*
* (non-Javadoc)
*
* @see org.concord.applesupport.AppleApplicationAdapter#about()
*/
public void about()
{
// TODO Auto-generated method stub
}
/*
* (non-Javadoc)
*
* @see org.concord.applesupport.AppleApplicationAdapter#preferences()
*/
public void preferences()
{
// TODO Auto-generated method stub
}
/*
* (non-Javadoc)
*
* @see org.concord.applesupport.AppleApplicationAdapter#quit()
*/
public void quit()
{
exitAction.actionPerformed(null);
}
} // @jve:decl-index=0:visual-constraint="10,10"
class HtmlFileFilter extends javax.swing.filechooser.FileFilter
{
public boolean accept(File f)
{
if (f == null)
return false;
if (f.isDirectory())
return true;
return (f.getName().toLowerCase().endsWith(".html"));
}
public String getDescription()
{
return "HTML files";
}
} // @jve:decl-index=0:visual-constraint="10,10"
|
package org.jdesktop.swingx;
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Frame;
import java.awt.GraphicsConfiguration;
import java.awt.GraphicsEnvironment;
import java.awt.Rectangle;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.util.regex.Pattern;
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.ActionMap;
import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.InputMap;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JComponent;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.KeyStroke;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import org.jdesktop.swingx.action.AbstractActionExt;
import org.jdesktop.swingx.action.ActionContainerFactory;
import org.jdesktop.swingx.action.BoundAction;
/**
* Simple FindDialog.
*
*
* PENDING: need to extract a common dialog.
* PENDING: the base search widget need not be a dialog!
*
* @author ??
* @author Jeanette Winzenburg
*/
public class JXFindDialog extends JDialog {
public static final String MATCH_WRAP_ACTION_COMMAND = "wrapSearch";
public static final String MATCH_BACKWARDS_ACTION_COMMAND = "backwardsSearch";
public static final String EXECUTE_FIND_ACTION_COMMAND = "executeSearch";
public static final String CLOSE_ACTION_COMMAND = "close";
// private static final Object ENTER_ACTION_COMMAND = null;
// private static final Object CANCEL_ACTION_COMMAND = null;
private Searchable searchable;
private JTextField searchField;
private JCheckBox matchCheck;
private JCheckBox wrapCheck;
private JCheckBox backCheck;
private PatternModel patternModel;
public JXFindDialog() {
this(null, null);
}
public JXFindDialog(Searchable searchable) {
this(searchable,
(searchable instanceof Component) ? (Component) searchable : null);
}
public JXFindDialog(Searchable searchable, Component component) {
super(component != null ?
(Frame)SwingUtilities.getWindowAncestor(component) : JOptionPane.getRootFrame(),
"Find in this component");
setSearchable(searchable);
locate();
init();
pack();
}
/**
* Sets the Searchable targeted with this dialog.
*
* @param searchable
*/
public void setSearchable(Searchable searchable) {
if ((this.searchable != null) && this.searchable.equals(searchable)) return;
Object old = this.searchable;
this.searchable = searchable;
setLastIndex(-1);
firePropertyChange("searchable", old, this.searchable);
}
private void locate() {
GraphicsConfiguration gc =
GraphicsEnvironment.getLocalGraphicsEnvironment().
getDefaultScreenDevice().getDefaultConfiguration();
Rectangle bounds = gc.getBounds();
int x = bounds.x+bounds.width/3;
int y = bounds.y+bounds.height/3;
setLocation(x, y);
}
private void init() {
initActions();
initComponents();
build();
bind();
}
private PatternModel getPatternModel() {
if (patternModel == null) {
patternModel = new PatternModel();
patternModel.addPropertyChangeListener(getPatternModelListener());
}
return patternModel;
}
/**
* creates and returns a PropertyChangeListener to the PatternModel.
*
* NOTE: the patternModel is totally under control of this class - currently
* there's no need to keep a reference to the listener.
*
* @return
*/
private PropertyChangeListener getPatternModelListener() {
PropertyChangeListener l = new PropertyChangeListener() {
public void propertyChange(PropertyChangeEvent evt) {
if ("pattern".equals(evt.getPropertyName())) {
refreshPatternMatchersFromModel();
}
}
};
return l;
}
/**
* callback method from listening to PatternModel.
*
*/
protected void refreshPatternMatchersFromModel() {
}
private DocumentListener getSearchFieldListener() {
DocumentListener l = new DocumentListener() {
public void changedUpdate(DocumentEvent ev) {
// JW - really?? we've a PlainDoc without Attributes
refreshModelFromDocument();
}
public void insertUpdate(DocumentEvent ev) {
refreshModelFromDocument();
}
public void removeUpdate(DocumentEvent ev) {
refreshModelFromDocument();
}
};
return l;
}
/**
* callback method from listening to searchField.
*
*/
protected void refreshModelFromDocument() {
getPatternModel().setRawText(searchField.getText());
}
private void bind() {
searchField.getDocument().addDocumentListener(getSearchFieldListener());
ActionContainerFactory factory = new ActionContainerFactory(null);
factory.configureButton(matchCheck,
(AbstractActionExt) getAction(JXSearchPanel.MATCH_CASE_ACTION_COMMAND),
null);
factory.configureButton(wrapCheck,
(AbstractActionExt) getAction(MATCH_WRAP_ACTION_COMMAND),
null);
factory.configureButton(backCheck,
(AbstractActionExt) getAction(MATCH_BACKWARDS_ACTION_COMMAND),
null);
}
/**
* Action callback for Find action.
*/
public void doFind() {
doFind(getPatternModel().isBackwards());
}
public void doFind(boolean backwards) {
if (searchable == null) return;
setLastIndex(searchable.search(getPattern(), getLastIndex(), backwards));
if (getLastIndex() == -1) {
boolean notFound = true;
if (isWrapping()) {
setLastIndex(searchable.search(getPattern(), -1, backwards));
notFound = getLastIndex() == -1;
}
if (notFound) {
JOptionPane.showMessageDialog(this, "Value not found");
}
}
}
private boolean isWrapping() {
return getPatternModel().isWrapping();
}
/**
* Action callback for Close action.
*/
public void doClose() {
JXFindDialog.this.dispose();
}
private void setLastIndex(int i) {
getPatternModel().setFoundIndex(i);
}
private int getLastIndex() {
return getPatternModel().getFoundIndex();
}
private Pattern getPattern() {
return getPatternModel().getPattern();
}
private void initActions() {
putAction(JXSearchPanel.MATCH_CASE_ACTION_COMMAND, createMatchCaseAction());
putAction(MATCH_WRAP_ACTION_COMMAND, createWrapAction());
putAction(MATCH_BACKWARDS_ACTION_COMMAND, createBackwardsAction());
// PENDING: factor a common dialog containing the following
putAction(EXECUTE_FIND_ACTION_COMMAND, createFindAction());
putAction(CLOSE_ACTION_COMMAND, createCloseAction());
}
/**
*
* @return
*/
private AbstractActionExt createMatchCaseAction() {
String actionName = getUIString(JXSearchPanel.MATCH_CASE_ACTION_COMMAND);
BoundAction action = new BoundAction(actionName,
JXSearchPanel.MATCH_CASE_ACTION_COMMAND);
action.setStateAction();
action.registerCallback(getPatternModel(), "setCaseSensitive");
action.setSelected(getPatternModel().isCaseSensitive());
return action;
}
/**
*
* @return
*/
private AbstractActionExt createWrapAction() {
String actionName = getUIString(MATCH_WRAP_ACTION_COMMAND);
BoundAction action = new BoundAction(actionName,
MATCH_WRAP_ACTION_COMMAND);
action.setStateAction();
action.registerCallback(getPatternModel(), "setWrapping");
action.setSelected(getPatternModel().isWrapping());
return action;
}
/**
*
* @return
*/
private AbstractActionExt createBackwardsAction() {
String actionName = getUIString(MATCH_BACKWARDS_ACTION_COMMAND);
BoundAction action = new BoundAction(actionName,
MATCH_BACKWARDS_ACTION_COMMAND);
action.setStateAction();
action.registerCallback(getPatternModel(), "setBackwards");
action.setSelected(getPatternModel().isWrapping());
return action;
}
/**
*
* @return
*/
private AbstractActionExt createFindAction() {
String actionName = getUIString(EXECUTE_FIND_ACTION_COMMAND);
BoundAction action = new BoundAction(actionName,
EXECUTE_FIND_ACTION_COMMAND);
action.registerCallback(this, "doFind");
return action;
}
/**
*
* @return
*/
private AbstractActionExt createCloseAction() {
String actionName = getUIString(CLOSE_ACTION_COMMAND);
BoundAction action = new BoundAction(actionName,
CLOSE_ACTION_COMMAND);
action.registerCallback(this, "doClose");
return action;
}
/**
* convenience wrapper to access rootPane's actionMap.
* @param key
* @param action
*/
private void putAction(Object key, Action action) {
getRootPane().getActionMap().put(key, action);
}
/**
* convenience wrapper to access rootPane's actionMap.
*
* @param key
* @return
*/
private Action getAction(Object key) {
return getRootPane().getActionMap().get(key);
}
/**
* tries to find a String value from the UIManager, prefixing the
* given key with the UIPREFIX.
*
* TODO: move to utilities?
*
* @param key
* @return the String as returned by the UIManager or key if the returned
* value was null.
*/
private String getUIString(String key) {
String text = UIManager.getString(PatternModel.SEARCH_PREFIX + key);
return text != null ? text : key;
}
/** create components.
*
*/
private void initComponents() {
searchField = new JTextField();
matchCheck = new JCheckBox();
wrapCheck = new JCheckBox();
backCheck = new JCheckBox();
}
private void build() {
getContentPane().add(createFieldPanel(), BorderLayout.CENTER);
getContentPane().add(createButtonPanel(), BorderLayout.SOUTH);
// Implementation of incremental search
/*
findText.getDocument().addDocumentListener(new DocumentListener() {
public void insertUpdate(DocumentEvent evt) {
doFind();
}
public void removeUpdate(DocumentEvent evt) {
doFind(true);
}
public void changedUpdate(DocumentEvent evt) {
}
});
*/
}
/**
* TODO: Strings should be removed from the UI
*/
private JComponent createFieldPanel() {
// Create components
JLabel label = new JLabel("Find Text: ");
label.setDisplayedMnemonicIndex(2);
label.setLabelFor(searchField);
Box lBox = Box.createVerticalBox();
lBox.add(label);
lBox.add(Box.createGlue());
Box rBox = Box.createVerticalBox();
rBox.add(searchField);
rBox.add(matchCheck);
rBox.add(wrapCheck);
rBox.add(backCheck);
Box box = Box.createHorizontalBox();
box.add(lBox);
box.add(rBox);
box.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
return box;
}
/**
* create the dialog button controls.
*
* PENDING: this should be factored to a common dialog support.
*
* @return
*/
private JPanel createButtonPanel() {
JPanel panel = new JPanel();
Action findAction = getAction(EXECUTE_FIND_ACTION_COMMAND);
Action closeAction = getAction(CLOSE_ACTION_COMMAND);
JButton findButton;
panel.add(findButton = new JButton(findAction));
panel.add(new JButton(closeAction));
KeyStroke enterKey = KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0, false);
KeyStroke escapeKey = KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0, false);
InputMap inputMap = getRootPane().getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);
inputMap.put(enterKey, EXECUTE_FIND_ACTION_COMMAND);
inputMap.put(escapeKey, CLOSE_ACTION_COMMAND);
getRootPane().setDefaultButton(findButton);
return panel;
}
// public boolean getMatchFlag() {
// return matchCheck.isSelected();
// /**
// * Public method for testing.
// * <p>
// * TODO: The state should probably be encapsulated by a model rather
// * that within the UI components.
// */
// public void setMatchFlag(boolean flag) {
// matchCheck.setSelected(flag);
// public boolean getWrapFlag() {
// return wrapCheck.isSelected();
// public void setWrapFlag(boolean flag) {
// wrapCheck.setSelected(flag);
// public boolean getBackwardsFlag() {
// return backCheck.isSelected();
// public void setBackwardsFlag(boolean flag) {
// backCheck.setSelected(flag);
// private class FindAction extends AbstractAction {
// public FindAction() {
// super("Find");
// public void actionPerformed(ActionEvent evt) {
// doFind();
// private class CloseAction extends AbstractAction {
// public CloseAction() {
// super("Close");
// public void actionPerformed(ActionEvent evt) {
// doClose();
private abstract class CheckAction extends AbstractAction {
public CheckAction(String name) {
super(name);
}
public void actionPerformed(ActionEvent evt) {
}
}
private class MatchAction extends CheckAction {
public MatchAction() {
super("Match upper/lower case");
putValue(Action.MNEMONIC_KEY, new Integer('M'));
}
}
private class WrapAction extends CheckAction {
public WrapAction() {
super("Wrap around");
putValue(Action.MNEMONIC_KEY, new Integer('W'));
}
}
private class BackwardAction extends CheckAction {
public BackwardAction() {
super("Search Backwards");
putValue(Action.MNEMONIC_KEY, new Integer('B'));
}
}
}
|
package org.jdesktop.swingx;
import java.awt.Cursor;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.Insets;
import java.awt.Rectangle;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.File;
import java.net.URL;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JFileChooser;
import javax.swing.JLabel;
import javax.swing.SwingUtilities;
/**
* <p>A panel that draws an image. The standard (and currently only supported)
* mode is to draw the specified image starting at position 0,0 in the
* panel. The component&s preferred size is based on the image, unless
* explicitly set by the user.</p>
*
* <p>In the future, the JXImagePanel will also support tiling of images,
* scaling, resizing, cropping, segways etc.</p>
*
* <p>This component also supports allowing the user to set the image. If the
* <code>JXImagePanel</code> is editable, then when the user clicks on the
* <code>JXImagePanel</code> a FileChooser is shown allowing the user to pick
* some other image to use within the <code>JXImagePanel</code>.</p>
*
* <p>Images to be displayed can be set based on URL, Image, etc.
*
* @author rbair
*/
public class JXImagePanel extends JXPanel {
public static enum Style {CENTERED, TILED, SCALED, SCALED_KEEP_ASPECT_RATIO};
private static final Logger LOG = Logger.getLogger(JXImagePanel.class
.getName());
/**
* Text informing the user that clicking on this component will allow them to set the image
*/
private static final String TEXT = "<html><i><b>Click here<br>to set the image</b></i></html>";
/**
* The image to draw
*/
private Image img;
/**
* If true, then the image can be changed. Perhaps a better name is
* "readOnly", but editable was chosen to be more consistent
* with other Swing components.
*/
private boolean editable = false;
/**
* The mouse handler that is used if the component is editable
*/
private MouseHandler mhandler = new MouseHandler();
/**
* If not null, then the user has explicitly set the preferred size of
* this component, and this should be honored
*/
private Dimension preferredSize;
/**
* Specifies how to draw the image, i.e. what kind of Style to use
* when drawing
*/
private Style style = Style.CENTERED;
public JXImagePanel() {
}
public JXImagePanel(URL imageUrl) {
try {
setImage(ImageIO.read(imageUrl));
} catch (Exception e) {
//TODO need convert to something meaningful
LOG.log(Level.WARNING, "", e);
}
}
/**
* Sets the image to use for the background of this panel. This image is
* painted whether the panel is opaque or translucent.
* @param image if null, clears the image. Otherwise, this will set the
* image to be painted. If the preferred size has not been explicitly set,
* then the image dimensions will alter the preferred size of the panel.
*/
public void setImage(Image image) {
if (image != img) {
Image oldImage = img;
img = image;
firePropertyChange("image", oldImage, img);
invalidate();
repaint();
}
}
/**
* @return the image used for painting the background of this panel
*/
public Image getImage() {
return img;
}
/**
* @param editable
*/
public void setEditable(boolean editable) {
if (editable != this.editable) {
//if it was editable, remove the mouse handler
if (this.editable) {
removeMouseListener(mhandler);
}
this.editable = editable;
//if it is now editable, add the mouse handler
if (this.editable) {
addMouseListener(new MouseHandler());
}
setToolTipText(editable ? TEXT : "");
firePropertyChange("editable", !editable, editable);
repaint();
}
}
/**
* @return whether the image for this panel can be changed or not via
* the UI. setImage may still be called, even if <code>isEditable</code>
* returns false.
*/
public boolean isEditable() {
return editable;
}
/**
* Sets what style to use when painting the image
*
* @param s
*/
public void setStyle(Style s) {
if (style != s) {
Style oldStyle = style;
style = s;
firePropertyChange("style", oldStyle, s);
repaint();
}
}
/**
* @return the Style used for drawing the image (CENTERED, TILED, etc).
*/
public Style getStyle() {
return style;
}
public void setPreferredSize(Dimension pref) {
preferredSize = pref;
super.setPreferredSize(pref);
}
public Dimension getPreferredSize() {
if (preferredSize == null && img != null) {
//it has not been explicitly set, so return the width/height of the image
int width = img.getWidth(null);
int height = img.getHeight(null);
if (width == -1 || height == -1) {
return super.getPreferredSize();
}
return new Dimension(width, height);
} else {
return super.getPreferredSize();
}
}
/**
* Overriden to paint the image on the panel
*/
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D)g;
if (img != null) {
final int imgWidth = img.getWidth(null);
final int imgHeight = img.getHeight(null);
if (imgWidth == -1 || imgHeight == -1) {
//image hasn't completed loading, return
return;
}
Insets insets = getInsets();
final int pw = getWidth() - insets.left - insets.right;
final int ph = getHeight() - insets.top - insets.bottom;
switch (style) {
case CENTERED:
Rectangle clipRect = g2.getClipBounds();
int imageX = (pw - imgWidth) / 2 + insets.left;
int imageY = (ph - imgHeight) / 2 + insets.top;
Rectangle r = SwingUtilities.computeIntersection(imageX, imageY, imgWidth, imgHeight, clipRect);
if (r.x == 0 && r.y == 0 && (r.width == 0 || r.height == 0)) {
return;
}
//I have my new clipping rectangle "r" in clipRect space.
//It is therefore the new clipRect.
clipRect = r;
//since I have the intersection, all I need to do is adjust the
//x & y values for the image
int txClipX = clipRect.x - imageX;
int txClipY = clipRect.y - imageY;
int txClipW = clipRect.width;
int txClipH = clipRect.height;
g2.drawImage(img, clipRect.x, clipRect.y, clipRect.x + clipRect.width, clipRect.y + clipRect.height,
txClipX, txClipY, txClipX + txClipW, txClipY + txClipH, null);
break;
case TILED:
case SCALED:
g2.drawImage(img, insets.left, insets.top, pw, ph, null);
break;
case SCALED_KEEP_ASPECT_RATIO:
int w;
int h;
if ((imgWidth - pw) > (imgHeight - ph)) {
w = pw;
final float ratio = ((float)w) / ((float)imgWidth);
h = (int)(imgHeight * ratio);
} else {
h = ph;
final float ratio = ((float)h) / ((float)imgHeight);
w = (int)(imgWidth * ratio);
}
final int x = (pw - w) / 2 + insets.left;
final int y = (ph - h) / 2 + insets.top;
g2.drawImage(img, x, y, w, h, null);
break;
default:
LOG.fine("unimplemented");
g2.drawImage(img, insets.left, insets.top, this);
break;
}
}
}
/**
* Handles click events on the component
*/
private class MouseHandler extends MouseAdapter {
private Cursor oldCursor;
private JFileChooser chooser;
public void mouseClicked(MouseEvent evt) {
if (chooser == null) {
chooser = new JFileChooser();
}
int retVal = chooser.showOpenDialog(JXImagePanel.this);
if (retVal == JFileChooser.APPROVE_OPTION) {
File file = chooser.getSelectedFile();
try {
setImage(new ImageIcon(file.toURI().toURL()).getImage());
} catch (Exception ex) {
}
}
}
public void mouseEntered(MouseEvent evt) {
if(evt.getSource() instanceof JLabel) {
JLabel label = (JLabel)evt.getSource();
if (oldCursor == null) {
oldCursor = label.getCursor();
label.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
}
}
}
public void mouseExited(MouseEvent evt) {
JLabel label = (JLabel)evt.getSource();
if (oldCursor != null) {
label.setCursor(oldCursor);
oldCursor = null;
}
}
}
}
|
package jmetest.renderer.loader;
import com.jme.scene.model.SAXReader;
import com.jme.app.SimpleGame;
import com.jme.renderer.ColorRGBA;
import java.io.File;
import java.io.IOException;
public class TestXMLLoader extends SimpleGame{
public static void main(String[] args){
new TestXMLLoader().start();
}
protected void simpleInitGame() {
lightState.get(0).setSpecular(new ColorRGBA(1,1,1,1));
SAXReader r=new SAXReader();
try {
r.loadXML(new File("CVS root/data/XML docs/SampleXMLScene.xml").toURL().openStream());
} catch (IOException e) {
System.out.println("bad File exception" + e.getCause() + "*" + e.getMessage());
}
rootNode.attachChild(r.fetchCopy());
}
}
|
package backend.resource;
import backend.IssueMetadata;
import backend.resource.serialization.SerializableIssue;
import org.apache.logging.log4j.Logger;
import org.eclipse.egit.github.core.Issue;
import org.eclipse.egit.github.core.Label;
import org.eclipse.egit.github.core.PullRequest;
import prefs.Preferences;
import util.HTLog;
import util.Utility;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
import static util.Utility.replaceNull;
/**
* The guidelines in this class apply to all TurboResources.
*/
public class TurboIssue {
private static final Logger logger = HTLog.get(TurboIssue.class);
public static final String STATE_CLOSED = "closed";
public static final String STATE_OPEN = "open";
/**
* Serialized fields.
* <p>
* Must have reasonable, NON-NULL defaults.
* Should be primitive types, or at least easily-serializable ones.
* Should be specified in order.
* Should be immutable as much as possible.
*/
// Immutable
private final int id;
private final String creator;
private final LocalDateTime createdAt;
private final boolean isPullRequest;
// Mutable
private String title;
private String description;
private LocalDateTime updatedAt;
private int commentCount;
private boolean isOpen;
private Optional<String> assignee;
private List<String> labels;
private Optional<Integer> milestone;
/**
* Metadata associated with issues that is not serialized.
*/
@SuppressWarnings("unused")
private void ______TRANSIENT_FIELDS______() {}
private final String repoId;
private IssueMetadata metadata;
private Optional<LocalDateTime> markedReadAt;
/* This field records the most recently modified time of the issue's labels or state. Any method that updates
the labels must also update this field. If this is empty, updatedAt time is used instead */
private Optional<LocalDateTime> labelsLastModifiedAt = Optional.empty();
private Optional<LocalDateTime> milestoneLastModifiedAt = Optional.empty();
private Optional<LocalDateTime> stateLastModifiedAt = Optional.empty();
@SuppressWarnings("unused")
private void ______CONSTRUCTORS______() {}
/**
* Default constructor: provides reasonable defaults for things.
*/
public TurboIssue(String repoId, int id, String title) {
this.id = id;
this.creator = "";
this.createdAt = LocalDateTime.now();
this.isPullRequest = false;
mutableFieldDefaults();
this.title = title;
this.repoId = repoId;
}
/**
* Immutable-conscious constructor.
*/
public TurboIssue(String repoId, int id, String title,
String creator, LocalDateTime createdAt, boolean isPullRequest) {
this.id = id;
this.creator = creator;
this.createdAt = createdAt;
this.isPullRequest = isPullRequest;
mutableFieldDefaults();
this.title = title;
this.repoId = repoId;
}
// Copy constructor
public TurboIssue(TurboIssue issue) {
this.id = issue.id;
this.title = issue.title;
this.creator = issue.creator;
this.createdAt = issue.createdAt;
this.isPullRequest = issue.isPullRequest;
this.description = issue.description;
this.updatedAt = replaceNull(issue.updatedAt, this.createdAt);
this.commentCount = issue.commentCount;
this.isOpen = issue.isOpen;
this.assignee = issue.assignee;
this.labels = new ArrayList<>(issue.labels);
this.milestone = issue.milestone;
this.metadata = issue.metadata;
this.repoId = issue.repoId;
this.markedReadAt = issue.markedReadAt;
this.labelsLastModifiedAt = Optional.of(issue.getLabelsLastModifiedAt());
this.stateLastModifiedAt = Optional.of(issue.getStateLastModifiedAt());
}
public TurboIssue(String repoId, Issue issue) {
this.id = issue.getNumber();
this.title = issue.getTitle() == null
? ""
: issue.getTitle();
this.creator = issue.getUser().getLogin();
this.createdAt = Utility.dateToLocalDateTime(issue.getCreatedAt());
this.isPullRequest = isPullRequest(issue);
this.description = issue.getBody() == null
? ""
: issue.getBody();
this.updatedAt = issue.getUpdatedAt() != null ?
Utility.dateToLocalDateTime(issue.getUpdatedAt()) : this.createdAt;
this.commentCount = issue.getComments();
this.isOpen = issue.getState().equals(STATE_OPEN);
this.assignee = issue.getAssignee() == null
? Optional.empty()
: Optional.of(issue.getAssignee().getLogin());
this.labels = issue.getLabels().stream()
.map(Label::getName)
.collect(Collectors.toList());
this.milestone = issue.getMilestone() == null
? Optional.empty()
: Optional.of(issue.getMilestone().getNumber());
this.metadata = IssueMetadata.empty();
this.repoId = repoId;
this.markedReadAt = Optional.empty();
}
public TurboIssue(String repoId, SerializableIssue issue) {
this.id = issue.getId();
this.creator = issue.getCreator();
this.createdAt = issue.getCreatedAt();
this.isPullRequest = issue.isPullRequest();
this.title = issue.getTitle();
this.description = issue.getDescription();
this.updatedAt = replaceNull(issue.getUpdatedAt(), this.createdAt);
this.commentCount = issue.getCommentCount();
this.isOpen = issue.isOpen();
this.assignee = issue.getAssignee();
this.labels = issue.getLabels();
this.milestone = issue.getMilestone();
this.metadata = IssueMetadata.empty();
this.repoId = repoId;
this.markedReadAt = Optional.empty();
}
@SuppressWarnings("unused")
private void ______CONSTRUCTOR_HELPER_FUNCTIONS______() {}
private static boolean isPullRequest(Issue issue) {
return issue.getPullRequest() != null && issue.getPullRequest().getUrl() != null;
}
private void mutableFieldDefaults() {
this.title = "";
this.description = "";
this.updatedAt = replaceNull(this.createdAt, LocalDateTime.now());
this.commentCount = 0;
this.isOpen = true;
this.assignee = Optional.empty();
this.labels = new ArrayList<>();
this.milestone = Optional.empty();
this.metadata = IssueMetadata.empty();
this.markedReadAt = Optional.empty();
}
/**
* Transient state may not always be transferred between issues. For example,
* when an issue is updated, the new issue is constructed from an external object,
* not an existing issue, so transient state on the old one is lost if the old issue
* is just replaced by the new. This method is required in such cases.
*
* @param fromIssue
*/
private void transferTransientState(TurboIssue fromIssue) {
this.metadata = fromIssue.metadata.invalidate();
this.markedReadAt = fromIssue.markedReadAt;
}
/**
* Reconciles content elements in this issue with {@code otherIssue} by taking
* the most recently updated elements based on their modified time.
*
* @param otherIssue
*/
private void reconcile(TurboIssue otherIssue) {
logger.info(String.format("Reconciling issue %s in %s", this, this.getRepoId()));
this.reconcileLabels(otherIssue);
}
/**
* See also {@link #reconcile(TurboIssue)}
*
* @param otherIssue
*/
private void reconcileLabels(TurboIssue otherIssue) {
LocalDateTime thisIssueLabelsModifiedAt = this.getLabelsLastModifiedAt();
LocalDateTime otherIssueLabelsModifiedAt = otherIssue.getLabelsLastModifiedAt();
if (thisIssueLabelsModifiedAt.isBefore(otherIssueLabelsModifiedAt)) {
logger.info(String.format("Issue %s's labels %s are stale, replacing with %s",
this, this.getLabels(), otherIssue.getLabels()));
this.labels = otherIssue.getLabels();
this.labelsLastModifiedAt = Optional.of(otherIssue.getLabelsLastModifiedAt());
}
}
/**
* Conceptually, operations on issues. They should only modify non-serialized fields.
*/
@SuppressWarnings("unused")
private void ______METHODS______() {}
@Override
public String toString() {
return repoId + "
}
/**
* Takes lists of TurboIssues and reconciles the changes between them,
* returning a list of TurboIssues with updates from the second.
*
* @param existing
* @param changed
*/
public static List<TurboIssue> reconcile(List<TurboIssue> existing, List<TurboIssue> changed) {
List<TurboIssue> existingCopy = new ArrayList<>(existing);
for (TurboIssue issue : changed) {
int id = issue.getId();
Optional<Integer> correspondingIssueIndex = findIssueWithId(existingCopy, id);
if (!correspondingIssueIndex.isPresent()) {
existingCopy.add(new TurboIssue(issue));
} else {
TurboIssue existingIssue = existingCopy.get(correspondingIssueIndex.get());
TurboIssue newIssue = new TurboIssue(issue);
// newIssue is constructed from an external Issue object.
// It won't have the transient state that its TurboIssue
// counterpart has, so we have to explicitly transfer it.
newIssue.transferTransientState(existingIssue);
newIssue.reconcile(existingIssue);
existingCopy.set(correspondingIssueIndex.get(), newIssue);
}
}
return existingCopy;
}
/**
* Updates data for issues with corresponding pull requests. Original list of
* issues and original issue instances are not mutated
*
* @param issues
* @param pullRequests
* @return a new list of issues
*/
public static List<TurboIssue> combineWithPullRequests(List<TurboIssue> issues,
List<PullRequest> pullRequests) {
List<TurboIssue> issuesCopy = new ArrayList<>(issues);
for (PullRequest pullRequest : pullRequests) {
int id = pullRequest.getNumber();
Optional<Integer> corresponding = findIssueWithId(issuesCopy, id);
if (corresponding.isPresent()) {
TurboIssue issue = issuesCopy.get(corresponding.get());
issuesCopy.set(corresponding.get(), issue.combineWithPullRequest(pullRequest));
} else {
String errorMsg = "No corresponding issue for pull request " + pullRequest;
logger.error(errorMsg);
}
}
return issuesCopy;
}
/**
* Combines data from a corresponding pull request with data in this issue
* This method returns a new combined issue and does not mutate this issue
*
* @param pullRequest
* @return new new combined issue
*/
public TurboIssue combineWithPullRequest(PullRequest pullRequest) {
TurboIssue newIssue = new TurboIssue(this);
if (pullRequest.getUpdatedAt() == null) {
return newIssue;
}
LocalDateTime pullRequestUpdatedAt = Utility.dateToLocalDateTime(pullRequest.getUpdatedAt());
if (pullRequestUpdatedAt.isBefore(newIssue.getUpdatedAt())) {
return newIssue;
}
newIssue.setUpdatedAt(pullRequestUpdatedAt);
return newIssue;
}
/**
* Finds the index of an issue with specified id in a list of issues
*
* @param issues
* @param id
* @return the list's index of the issue or empty of there is no issue with such id in the list
*/
public static Optional<Integer> findIssueWithId(List<TurboIssue> issues, int id) {
for (int i = 0; i < issues.size(); i++) {
if (issues.get(i).getId() == id) {
return Optional.of(i);
}
}
return Optional.empty();
}
/**
* Matching is done by matching all words separated by space in query
*
* @param issues
* @param query
* @return list of issues that contains the query
*/
public static List<TurboIssue> getMatchedIssues(List<TurboIssue> issues, String query) {
List<String> queries = Arrays.asList(query.split("\\s"));
return issues.stream()
.filter(i -> Utility.containsIgnoreCase(i.getTitle() + " " + i.getId(), queries))
.collect(Collectors.toList());
}
/**
* @param issues
* @param query
* @return first issue that matches the given query
*/
public static Optional<TurboIssue> getFirstMatchingIssue(List<TurboIssue> issues, String query) {
return getMatchedIssues(issues, query).stream().findFirst();
}
@SuppressWarnings("unused")
private void ______BOILERPLATE______() {}
public String getRepoId() {
return repoId;
}
public int getId() {
return id;
}
public String getCreator() {
return creator;
}
public LocalDateTime getCreatedAt() {
return createdAt;
}
public boolean isPullRequest() {
return isPullRequest;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public LocalDateTime getUpdatedAt() {
return updatedAt;
}
public void setUpdatedAt(LocalDateTime updatedAt) {
this.updatedAt = replaceNull(updatedAt, this.createdAt);
}
public int getCommentCount() {
return commentCount;
}
public void setCommentCount(int commentCount) {
this.commentCount = commentCount;
}
public boolean isOpen() {
return isOpen;
}
public void setOpen(boolean isOpen) {
this.isOpen = isOpen;
stateLastModifiedAt = Optional.of(LocalDateTime.now());
}
public Optional<String> getAssignee() {
return assignee;
}
public void setAssignee(String assignee) {
this.assignee = Optional.of(assignee);
}
public void setAssignee(TurboUser assignee) {
setAssignee(assignee.getLoginName());
}
public List<String> getLabels() {
return labels;
}
public void setLabels(List<String> labels) {
this.labels = labels;
this.labelsLastModifiedAt = Optional.of(LocalDateTime.now());
}
public LocalDateTime getLabelsLastModifiedAt() {
return this.labelsLastModifiedAt.orElse(getUpdatedAt());
}
public LocalDateTime getMilestoneLastModifiedAt() {
return this.milestoneLastModifiedAt.orElse(getUpdatedAt());
}
public LocalDateTime getStateLastModifiedAt() {
return stateLastModifiedAt.orElse(getUpdatedAt());
}
public void addLabel(String label) {
this.labels.add(label);
this.labelsLastModifiedAt = Optional.of(LocalDateTime.now());
}
public void addLabel(TurboLabel label) {
addLabel(label.getFullName());
this.labelsLastModifiedAt = Optional.of(LocalDateTime.now());
}
public Optional<Integer> getMilestone() {
return milestone;
}
public void setMilestoneById(Integer milestone) {
this.milestone = Optional.of(milestone);
this.milestoneLastModifiedAt = Optional.of(LocalDateTime.now());
}
public void setMilestone(TurboMilestone milestone) {
setMilestoneById(milestone.getId());
this.milestoneLastModifiedAt = Optional.of(LocalDateTime.now());
}
public void removeMilestone() {
this.milestone = Optional.empty();
}
public IssueMetadata getMetadata() {
return metadata;
}
public void setMetadata(IssueMetadata metadata) {
this.metadata = metadata;
}
public Optional<LocalDateTime> getMarkedReadAt() {
return markedReadAt;
}
public void setMarkedReadAt(Optional<LocalDateTime> markedReadAt) {
this.markedReadAt = markedReadAt;
}
public boolean isCurrentlyRead() {
if (!getMarkedReadAt().isPresent()) {
return false;
}
return getMarkedReadAt().get().isAfter(getUpdatedAt());
}
public void markAsRead(Preferences prefs) {
LocalDateTime now = LocalDateTime.now();
setMarkedReadAt(Optional.of(now));
prefs.setMarkedReadAt(getRepoId(), getId(), getMarkedReadAt().get());
}
public void markAsUnread(Preferences prefs) {
setMarkedReadAt(Optional.empty());
prefs.clearMarkedReadAt(getRepoId(), getId());
}
/**
* Metadata is not considered for equality.
* In general only serialised fields are.
*/
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
TurboIssue issue = (TurboIssue) o;
return commentCount == issue.commentCount &&
id == issue.id && isOpen == issue.isOpen &&
isPullRequest == issue.isPullRequest &&
!(assignee != null ? !assignee.equals(issue.assignee) : issue.assignee != null) &&
!(createdAt != null ? !createdAt.equals(issue.createdAt) : issue.createdAt != null) &&
!(creator != null ? !creator.equals(issue.creator) : issue.creator != null) &&
!(description != null ? !description.equals(issue.description) : issue.description != null) &&
!(labels != null ? !labels.equals(issue.labels) : issue.labels != null) &&
!(milestone != null ? !milestone.equals(issue.milestone) : issue.milestone != null) &&
!(title != null ? !title.equals(issue.title) : issue.title != null) &&
!(updatedAt != null ? !updatedAt.equals(issue.updatedAt) : issue.updatedAt != null) &&
!(markedReadAt != null ? !markedReadAt.equals(issue.markedReadAt) : issue.markedReadAt != null);
}
@Override
public int hashCode() {
int result = id;
result = 31 * result + (creator != null ? creator.hashCode() : 0);
result = 31 * result + (createdAt != null ? createdAt.hashCode() : 0);
result = 31 * result + (isPullRequest ? 1 : 0);
result = 31 * result + (title != null ? title.hashCode() : 0);
result = 31 * result + (description != null ? description.hashCode() : 0);
result = 31 * result + (updatedAt != null ? updatedAt.hashCode() : 0);
result = 31 * result + (markedReadAt != null ? markedReadAt.hashCode() : 0);
result = 31 * result + commentCount;
result = 31 * result + (isOpen ? 1 : 0);
result = 31 * result + (assignee != null ? assignee.hashCode() : 0);
result = 31 * result + (labels != null ? labels.hashCode() : 0);
result = 31 * result + (milestone != null ? milestone.hashCode() : 0);
return result;
}
}
|
package com.amee.base.engine;
import com.amee.base.transaction.TransactionController;
import org.apache.commons.cli.*;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.joda.time.DateTimeZone;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.tanukisoftware.wrapper.WrapperListener;
import org.tanukisoftware.wrapper.WrapperManager;
import java.util.TimeZone;
public class Engine implements WrapperListener {
private final Log log = LogFactory.getLog(getClass());
private ClassPathXmlApplicationContext springContext;
private TransactionController transactionController;
// These are used to determine the PID of the instance in the init script.
private String appName = "amee";
private String serverName = "localhost";
private String instanceName = "live";
public Engine() {
super();
}
public Engine(String appName, String serverName, String instanceName) {
this();
this.appName = appName;
this.serverName = serverName;
this.instanceName = instanceName;
}
/**
* A main method which can be used to start an {@link Engine}.
*
* @param args command line arguments
*/
public static void main(String[] args) {
start(new Engine(), args);
}
/**
* Start the application via {@link WrapperManager}.
*
* @param wrapperListener to use when starting the application.
* @param args command line arguments
*/
protected static void start(WrapperListener wrapperListener, String[] args) {
WrapperManager.start(wrapperListener, args);
}
/**
* Start the application. This implements the start method of {@link WrapperListener}.
*
* @param args command line arguments
* @return error code
*/
@Override
public Integer start(String[] args) {
parseOptions(args);
log.debug("Starting Engine...");
// Initialise Spring ApplicationContext.
springContext = new ClassPathXmlApplicationContext(new String[]{"applicationContext*.xml"});
// Initialise TransactionController (for controlling Spring).
transactionController = (TransactionController) springContext.getBean("transactionController");
// Do onStart callback wrapped in a transaction.
boolean started;
try {
transactionController.begin(true);
started = onStart();
log.debug("...Engine started.");
} finally {
transactionController.end();
}
// Handle result.
if (started) {
return null;
} else {
// An arbitrary error code to indicate startup failure.
return 1;
}
}
/**
* Parse the command line options and store in private properties.
*
* @param args the argument list
*/
protected void parseOptions(String[] args) {
CommandLine line = null;
CommandLineParser parser = new GnuParser();
Options options = new Options();
// Define appName option.
Option appNameOpt = OptionBuilder.withArgName("appName")
.hasArg()
.withDescription("The app name")
.create("appName");
appNameOpt.setRequired(true);
options.addOption(appNameOpt);
// Define serverName option.
Option serverNameOpt = OptionBuilder.withArgName("serverName")
.hasArg()
.withDescription("The server name")
.create("serverName");
serverNameOpt.setRequired(true);
options.addOption(serverNameOpt);
// Define instanceName option.
Option instanceNameOpt = OptionBuilder.withArgName("instanceName")
.hasArg()
.withDescription("The instance name")
.create("instanceName");
instanceNameOpt.setRequired(true);
options.addOption(instanceNameOpt);
// Define timeZone option.
Option timeZoneOpt = OptionBuilder.withArgName("timeZone")
.hasArg()
.withDescription("The time zone")
.create("timeZone");
timeZoneOpt.setRequired(false);
options.addOption(timeZoneOpt);
// Parse the options.
try {
line = parser.parse(options, args);
} catch (ParseException exp) {
new HelpFormatter().printHelp("java " + this.getClass().getName(), options);
System.exit(-1);
}
// Handle appName.
if (line.hasOption(appNameOpt.getOpt())) {
appName = line.getOptionValue(appNameOpt.getOpt());
}
// Handle serverName.
if (line.hasOption(serverNameOpt.getOpt())) {
serverName = line.getOptionValue(serverNameOpt.getOpt());
}
// Handle instanceName.
if (line.hasOption(instanceNameOpt.getOpt())) {
instanceName = line.getOptionValue(instanceNameOpt.getOpt());
}
// Handle timeZone.
if (line.hasOption(timeZoneOpt.getOpt())) {
String timeZoneStr = line.getOptionValue(timeZoneOpt.getOpt());
if (!StringUtils.isBlank(timeZoneStr)) {
TimeZone timeZone = TimeZone.getTimeZone(timeZoneStr);
if (timeZone != null) {
TimeZone.setDefault(timeZone);
DateTimeZone.setDefault(DateTimeZone.forTimeZone(timeZone));
}
}
}
log.info("parseOptions() Time Zone is: " + TimeZone.getDefault().getDisplayName() + " (" + TimeZone.getDefault().getID() + ")");
}
/**
* A callback for when the application has started.
*
* @return returns true if the application started successfully
*/
protected boolean onStart() {
// Do nothing.
return true;
}
/**
* A callback for when the application has shutdown.
*
* @return returns true if the application has shutdown successfully
*/
protected boolean onShutdown() {
// Stop Spring. Wait 500ms.
if (springContext != null) {
try {
springContext.stop();
springContext = null;
Thread.sleep(500);
} catch (Exception e) {
log.fatal("onStart() Caught Exception: " + e);
e.printStackTrace();
return false;
} catch (Throwable e) {
log.fatal("onStart() Caught Throwable: " + e);
e.printStackTrace();
return false;
}
}
return true;
}
/**
* Stop the application.
*
* @param exitCode system exit code
* @return system exit code
*/
@Override
public int stop(int exitCode) {
try {
log.debug("Stopping Engine...");
onShutdown();
log.debug("...Engine stopped.");
} catch (Exception e) {
log.error("Caught Exception: " + e, e);
}
return exitCode;
}
/**
* Callback for handling system control events.
*
* @param event the event code
*/
@Override
public void controlEvent(int event) {
log.debug("controlEvent() " + event);
// Do nothing.
}
public ApplicationContext getSpringContext() {
return springContext;
}
public TransactionController getTransactionController() {
return transactionController;
}
public String getAppName() {
return appName;
}
public String getServerName() {
return serverName;
}
public String getInstanceName() {
return instanceName;
}
}
|
package com.bob.coder.util;
public enum FileEnum {
SQL_XML("sqlXml.ftl", ".mapper", "Mapper.xml", true),
MODEL("model.ftl", ".entity", ".java", true),
MODEL_VO("modelVo.ftl", ".entity", "Vo.java", true),
QUERY("query.ftl", ".entity", "Query.java", true),
DAO("dao.ftl", ".mapper", "Mapper.java", true),
DAO_IMPL("daoImpl.ftl", ".dao.impl", "DaoImpl.java", true),
SERVICE("service.ftl", ".service", "Service.java", true),
SERVICE_IMPL("serviceImp.ftl", ".service.impl", "ServiceImpl.java", true),
CONTROLLER("controller.ftl", ".controller", "Controller.java", true),
LIST_PAGE("list.ftl", ".jsp", "List.jsp", true),
EDIT_PAGE("edit.ftl", ".jsp", "edit.jsp", true),
VIEW_PAGE("view.ftl", ".jsp", "View.jsp", true);
public String templateName;
public String packageName;
public String fileName;
public boolean isGenerate;
/**
* @param templateName
* @param packageName
* @param fileName
* @param isGenerate
*/
FileEnum(String templateName, String packageName, String fileName, boolean isGenerate) {
this.templateName = templateName;
this.packageName = packageName;
this.fileName = fileName;
this.isGenerate = isGenerate;
}
public static void main(String[] args) {
FileEnum[] values = FileEnum.values();
for (FileEnum e : values) {
e.isGenerate = false;
}
for (FileEnum e : values) {
System.out.println(e.fileName);
System.out.println(e.isGenerate);
}
}
}
|
package com.brettonw.bag;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import sun.reflect.ReflectionFactory;
import java.lang.reflect.*;
import java.util.*;
/**
* A tool to convert data types to and from BagObjects for serialization. It is designed to support
* primitives, Plain Old Java Object (POJO) classes, object classes with getters and setters,
* arrays, and array or map-based containers of one of the previously mentioned types. It explicitly
* supports BagObject and BagArray as well.
*/
public final class Serializer {
private static final Logger log = LogManager.getLogger (Serializer.class);
// the static interface
private static final String TYPE_KEY = "type";
private static final String VERSION_KEY = "v";
private static final String KEY_KEY = "key";
private static final String VALUE_KEY = "value";
// future changes might require the serializer to know a different type of encoding is expected.
// we use a two step version, where changes in the ".x" region don't require a new deserializer
// but for which we want old version of serialization to fail. changes in the "1." region
// indicate a completely new deserializer is needed. we will not ever support serializing to
// older formats (link against the old version of this package if you want that). we will decide
// whether or not to support multiple deserializer formats when the time comes.
private static final String SERIALIZER_VERSION_1 = "1.0";
private static final String SERIALIZER_VERSION = SERIALIZER_VERSION_1;
private static boolean isPrimitive (Class type) {
// an obvious check to do here is type.isPrimitive (), but that is never true because Java
// has boxed the primitives before they get here. So, we have to check for boxed primitives
// and strings as well
switch (type.getName ()) {
case "java.lang.Long": case "java.lang.Integer": case "java.lang.Short": case "java.lang.Byte":
case "java.lang.Character":
case "java.lang.Boolean":
case "java.lang.Double": case "java.lang.Float":
case "java.lang.String":
return true;
}
// it wasn't any of those, return false;
return false;
}
private static SerializationType serializationType (Class type) {
if (isPrimitive (type)) return SerializationType.PRIMITIVE;
if (type.isEnum ()) return SerializationType.ENUM;
if (type.isArray ()) return SerializationType.ARRAY;
if (Collection.class.isAssignableFrom (type)) return SerializationType.COLLECTION;
if (Map.class.isAssignableFrom (type)) return SerializationType.MAP;
if (BagObject.class.isAssignableFrom (type)) return SerializationType.BAG_OBJECT;
if (BagArray.class.isAssignableFrom (type)) return SerializationType.BAG_ARRAY;
// if it's none of the above...
return SerializationType.JAVA_OBJECT;
}
private static SerializationType serializationType (String typeString) throws ClassNotFoundException {
if (typeString.charAt (0) == '[') {
return SerializationType.ARRAY;
}
ClassLoader classLoader = ClassLoader.getSystemClassLoader ();
Class type = classLoader.loadClass (typeString);
return serializationType (type);
}
private static BagObject serializePrimitiveType (BagObject bagObject, Object object) {
return bagObject.put (VALUE_KEY, object);
}
private static BagObject serializeJavaEnumType (BagObject bagObject, Object object, Class type) {
return bagObject.put (VALUE_KEY, object.toString ());
}
private static BagObject serializeJavaObjectType (BagObject bagObject, Object object, Class type) {
// this bag object will hold the value(s) of the fields
BagObject value = new BagObject ();
// gather all of the fields declared; public, private, static, etc., then loop over them
Set<Field> fieldSet = new HashSet<> (Arrays.asList (type.getFields ()));
fieldSet.addAll (Arrays.asList (type.getDeclaredFields ()));
for (Field field : fieldSet) {
// check if the field is static, we don't want to serialize any static values, as this
// leads to recursion
if (! Modifier.isStatic (field.getModifiers ())) {
// force accessibility for serialization - this is an issue with the reflection API
// that we want to step around because serialization is assumed to be the primary
// goal, as opposed to viewing a way to workaround an API that needs to be over-
boolean accessible = field.isAccessible ();
field.setAccessible (true);
// get the name and type, and get the value to encode
try {
value.put (field.getName (), toBagObject (field.get (object)));
} catch (IllegalAccessException exception) {
// NOTE this shouldn't happen, per the comments above, and is untestable for
// purpose of measuring coverage
log.debug (exception);
}
// restore the accessibility - not 100% sure this is necessary, better be safe than
// sorry, right?
field.setAccessible (accessible);
}
}
return bagObject.put (VALUE_KEY, value);
}
private static BagObject serializeArrayType (BagObject bagObject, Object object) {
int length = Array.getLength (object);
BagArray value = new BagArray (length);
for (int i = 0; i < length; ++i) {
// at runtime, we don't know what the array type is, and frankly we don't care
value.add (toBagObject (Array.get (object, i)));
}
return bagObject.put (VALUE_KEY, value);
}
private static BagObject serializeMapType (BagObject bagObject, Map object) {
Object[] keys = object.keySet ().toArray ();
BagArray value = new BagArray (keys.length);
for (Object key : keys) {
Object item = object.get (key);
BagObject pair = new BagObject (2)
.put (KEY_KEY, toBagObject (key))
.put (VALUE_KEY, toBagObject (item));
value.add (pair);
}
return bagObject.put (VALUE_KEY, value);
}
/**
* Convert the given object to a BagObject representation that can be used to reconstitute the
* given object after serialization.
*
* @param object the target element to serialize. It must be one of the following: primitive,
* boxed-primitive, Plain Old Java Object (POJO) class, object class with getters
* and setters for all members, BagObject, BagArray, array, or list or map-based
* container of one of the previously mentioned types.
* @return A BagObject encapsulation of the target object, or null if the conversion failed.
*/
public static BagObject toBagObject (Object object) {
// fill out the header of the encapsulating bag
Class type = object.getClass ();
BagObject bagObject = new BagObject (3)
.put (TYPE_KEY, type.getName ())
.put (VERSION_KEY, SERIALIZER_VERSION);
// the next step depends on the actual type of what's being serialized
switch (serializationType (type)) {
case PRIMITIVE: bagObject = serializePrimitiveType (bagObject, object); break;
case ENUM: bagObject = serializeJavaEnumType (bagObject, object, type); break;
case BAG_OBJECT: bagObject = serializePrimitiveType (bagObject, object); break;
case BAG_ARRAY: bagObject = serializePrimitiveType (bagObject, object); break;
case JAVA_OBJECT: bagObject = serializeJavaObjectType (bagObject, object, type); break;
case COLLECTION: bagObject = serializeArrayType (bagObject, ((Collection) object).toArray ()); break;
case MAP: bagObject = serializeMapType (bagObject, (Map) object); break;
case ARRAY: bagObject = serializeArrayType (bagObject, object); break;
}
return bagObject;
}
@SuppressWarnings (value="unchecked")
private static Object deserializePrimitiveType (BagObject bagObject) throws ClassNotFoundException, NoSuchMethodException, IllegalAccessException, InstantiationException, InvocationTargetException {
String valueString = bagObject.getString (VALUE_KEY);
Class type = ClassLoader.getSystemClassLoader ().loadClass (bagObject.getString (TYPE_KEY));
// Character types don't have a constructor from a String, so we have to handle that as a
// special case. Fingers crossed we don't find any others
return (type.isAssignableFrom (Character.class)) ?
type.getConstructor (char.class).newInstance (valueString.charAt (0)) :
type.getConstructor (String.class).newInstance (valueString);
}
private static Object deserializeJavaEnumType (BagObject bagObject) throws ClassNotFoundException {
Class type = ClassLoader.getSystemClassLoader ().loadClass (bagObject.getString (TYPE_KEY));
return Enum.valueOf (type, bagObject.getString (VALUE_KEY));
}
private static Object deserializeJavaObjectType (BagObject bagObject) throws ClassNotFoundException, IllegalAccessException, NoSuchMethodException, InstantiationException, InvocationTargetException {
Object target = null;
// get the type
Class type = ClassLoader.getSystemClassLoader ().loadClass (bagObject.getString (TYPE_KEY));
// instantiate the object using the serialization interface, this should effectively create
// the object without any initialization. we will do that next.
try {
ReflectionFactory reflectionFactory = ReflectionFactory.getReflectionFactory ();
Constructor objectConstructor = Object.class.getDeclaredConstructor ();
Constructor constructor = reflectionFactory.newConstructorForSerialization (type, objectConstructor);
target = constructor.newInstance ();
} catch (Exception exception) {
log.error (exception);
}
// Wendy, is the water warm enough? Yes, Lisa. (Prince, RIP)
if (target != null) {
// gather all of the fields declared; public, private, static, etc., then loop over them
BagObject value = bagObject.getBagObject (VALUE_KEY);
Set<Field> fieldSet = new HashSet<> (Arrays.asList (type.getFields ()));
fieldSet.addAll (Arrays.asList (type.getDeclaredFields ()));
for (Field field : fieldSet) {
// only populate this field if we serialized it
if (value.has (field.getName ())) {
// force accessibility for serialization, as above... this should prevent the
boolean accessible = field.isAccessible ();
field.setAccessible (true);
// get the name and type, and set the value from the encode value
//log.trace ("Add " + field.getName () + " as " + field.getType ().getName ());
field.set (target, fromBagObject (value.getBagObject (field.getName ())));
// restore the accessibility - not 100% sure this is necessary, better be safe
// than sorry, right?
field.setAccessible (accessible);
}
}
}
return target;
}
@SuppressWarnings (value="unchecked")
private static Object deserializeCollectionType (BagObject bagObject) throws ClassNotFoundException, IllegalAccessException, InstantiationException {
Class type = ClassLoader.getSystemClassLoader ().loadClass (bagObject.getString (TYPE_KEY));
Collection target = (Collection) type.newInstance ();
BagArray value = bagObject.getBagArray (VALUE_KEY);
for (int i = 0, end = value.getCount (); i < end; ++i) {
target.add (fromBagObject (value.getBagObject (i)));
}
return target;
}
@SuppressWarnings (value="unchecked")
private static Object deserializeMapType (BagObject bagObject) throws ClassNotFoundException, IllegalAccessException, InstantiationException {
Class type = ClassLoader.getSystemClassLoader ().loadClass (bagObject.getString (TYPE_KEY));
Map target = (Map) type.newInstance ();
BagArray value = bagObject.getBagArray (VALUE_KEY);
for (int i = 0, end = value.getCount (); i < end; ++i) {
BagObject entry = value.getBagObject (i);
target.put (fromBagObject (entry.getBagObject (KEY_KEY)), fromBagObject (entry.getBagObject (VALUE_KEY)));
}
return target;
}
private static Class getArrayType (String typeName) throws ClassNotFoundException {
int arrayDepth = 0;
while (typeName.charAt (arrayDepth) == '[') { ++arrayDepth; }
switch (typeName.substring (arrayDepth)) {
case "B": return byte.class;
case "C": return char.class;
case "D": return double.class;
case "F": return float.class;
case "I": return int.class;
case "J": return long.class;
case "S": return short.class;
case "Z": return boolean.class;
case "Ljava.lang.Byte;": return Byte.class;
case "Ljava.lang.Character;": return Character.class;
case "Ljava.lang.Double;": return Double.class;
case "Ljava.lang.Float;": return Float.class;
case "Ljava.lang.Integer;": return Integer.class;
case "Ljava.lang.Long;": return Long.class;
case "Ljava.lang.Short;": return Short.class;
case "Ljava.lang.Boolean;": return Boolean.class;
}
// if we get here, the type is either a class name, or ???
if (typeName.charAt (arrayDepth) == 'L') {
ClassLoader classLoader = ClassLoader.getSystemClassLoader ();
int semiColon = typeName.indexOf (';');
typeName = typeName.substring (arrayDepth + 1, semiColon);
// note that this could throw ClassNotFound if the typeName is not legitimate.
return classLoader.loadClass (typeName);
}
// this will only happen if we are deserializing from modified source
throw new ClassNotFoundException(typeName);
}
private static int[] getArraySizes (BagObject bagObject) {
// figure the array dimension
String typeString = bagObject.getString (TYPE_KEY);
int dimension = 0;
while (typeString.charAt (dimension) == '[') { ++dimension; }
// create and populate the sizes array
int sizes[] = new int[dimension];
for (int i = 0; i < dimension; ++i) {
BagArray value = bagObject.getBagArray (VALUE_KEY);
sizes[i] = value.getCount ();
bagObject = value.getBagObject (0);
}
// return the result
return sizes;
}
private static void populateArray(Object target, BagObject bagObject) {
String classString = bagObject.getString (TYPE_KEY);
BagArray values = bagObject.getBagArray (VALUE_KEY);
for (int i = 0, end = values.getCount (); i < end; ++i) {
if (classString.charAt (1) == '[') {
// we should recur for each value
Object newTarget = Array.get (target, i);
BagObject newBagObject = values.getBagObject (i);
populateArray (newTarget, newBagObject);
} else {
Array.set (target, i, fromBagObject (values.getBagObject (i)));
}
}
}
private static Object deserializeArrayType (BagObject bagObject) throws ClassNotFoundException {
int[] arraySizes = getArraySizes (bagObject);
Class type = getArrayType (bagObject.getString (TYPE_KEY));
Object target = Array.newInstance (type, arraySizes);
populateArray (target, bagObject);
return target;
}
private static void checkVersion (String got) throws BadVersionException {
if (! got.equals (SERIALIZER_VERSION)) {
throw new BadVersionException (got, SERIALIZER_VERSION);
}
}
public static <WorkingType> WorkingType fromBagObject (BagObject bagObject) {
Object result = null;
try {
// we expect a future change might use a different approach to deserialization, so we
// check to be sure this is the version we are working to
checkVersion (bagObject.getString (VERSION_KEY));
switch (serializationType (bagObject.getString (TYPE_KEY))) {
case PRIMITIVE: result = deserializePrimitiveType (bagObject); break;
case ENUM: result = deserializeJavaEnumType (bagObject); break;
case BAG_OBJECT: result = bagObject.getBagObject (VALUE_KEY); break;
case BAG_ARRAY: result = bagObject.getBagArray (VALUE_KEY); break;
case JAVA_OBJECT: result = deserializeJavaObjectType (bagObject); break;
case COLLECTION: result = deserializeCollectionType (bagObject); break;
case MAP: result = deserializeMapType (bagObject); break;
case ARRAY: result = deserializeArrayType (bagObject); break;
}
}
catch (Exception exception) {
log.error (exception);
}
return (WorkingType) result;
}
}
|
package com.cube.storm.ui.view;
import com.cube.storm.ui.model.Model;
import com.cube.storm.ui.view.holder.DescriptionListItemHolder;
import com.cube.storm.ui.view.holder.Holder;
import com.cube.storm.ui.view.holder.ImageListItemHolder;
import com.cube.storm.ui.view.holder.ListFooterHolder;
import com.cube.storm.ui.view.holder.ListHeaderHolder;
import com.cube.storm.ui.view.holder.OrderedListItemHolder;
import com.cube.storm.ui.view.holder.StandardListItemHolder;
import com.cube.storm.ui.view.holder.TextListItemHolder;
import com.cube.storm.ui.view.holder.TitleListItemHolder;
/**
* This is the enum class with the list of all supported view types, their model classes and their
* corresponding view holder class. This list should not be modified or overridden
*
* @author Callum Taylor
* @project Storm Test
*/
public enum View
{
/**
* Private views - These are not driven by the CMS, these are internal classes derived from
* the list model.
*/
_ListHeader(com.cube.storm.ui.model.list.List.ListHeader.class, ListHeaderHolder.class),
_ListFooter(com.cube.storm.ui.model.list.List.ListFooter.class, ListFooterHolder.class),
List(com.cube.storm.ui.model.list.List.class, null),
TextListItem(com.cube.storm.ui.model.list.TextListItem.class, TextListItemHolder.class),
ImageListItem(com.cube.storm.ui.model.list.ImageListItem.class, ImageListItemHolder.class),
TitleListItem(com.cube.storm.ui.model.list.TitleListItem.class, TitleListItemHolder.class),
DescriptionListItem(com.cube.storm.ui.model.list.DescriptionListItem.class, DescriptionListItemHolder.class),
StandardListItem(com.cube.storm.ui.model.list.StandardListItem.class, StandardListItemHolder.class),
OrderedListItem(com.cube.storm.ui.model.list.OrderedListItem.class, OrderedListItemHolder.class),
ListPage(com.cube.storm.ui.model.page.ListPage.class, null),
/**
* Properties
*/
Image(com.cube.storm.ui.model.property.BundleImageProperty.class, null);
private Class<? extends Model> model;
private Class<? extends Holder> holder;
private View(Class<? extends Model> model, Class<? extends Holder> holder)
{
this.model = model;
this.holder = holder;
}
/**
* @return Gets the holder class of the view
*/
public Class<? extends Holder> getHolderClass()
{
return holder;
}
/**
* @return Gets the model class of the view
*/
public Class<? extends Model> getModelClass()
{
return model;
}
}
|
package com.mapcode.example;
import com.mapcode.Mapcode;
import com.mapcode.MapcodeInfo;
import com.mapcode.ParentTerritory;
import com.mapcode.Point;
import com.mapcode.Territory;
import com.mapcode.UnknownMapcodeException;
import com.mapcode.UnknownTerritoryException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.List;
/**
* This class serves as an example of how to use the Mapcode Java library.
*/
public class Example {
private static final Logger LOG = LoggerFactory.getLogger(Example.class);
/**
* Main method.
*
* @param args Arguments (unused).
*/
public static void main(final String[] args) throws UnknownTerritoryException {
// Example 1 - Disambiguate MN in several conditions.
LOG.info("Example 1 (disambuate MN, Minnesota):");
final String iso = "MN";
LOG.info("ISO code {} without context : {}", iso, Territory.fromString(iso).toString());
LOG.info("ISO code {} in USA context : {}", iso, Territory.fromString(iso, ParentTerritory.USA).toString());
LOG.info("ISO code {} in IND context : {}", iso, Territory.fromString(iso, ParentTerritory.IND).toString());
LOG.info("ISO code {} in RUS context : {}", iso, Territory.fromString(iso, ParentTerritory.RUS).toString());
LOG.info("");
// Example 2 - Get the Mapcode Territory for a territory abbreviation 'isocode',
// e.g. entered by the user.
final String isocode = "NLD"; // Abbreviation for The Netherlands
final Territory mapcodeTerritory = Territory.fromString(isocode);
// Example 3 - print the full English name of the territory.
LOG.info("Example 2/3:");
LOG.info("Territory {}: {}", isocode, mapcodeTerritory.getFullName());
LOG.info("");
// Example 4 - Decode some Mapcodes in this territory.
LOG.info("Example 4 (Decode examples):");
String mapcode = "49.4V";
try {
final Point p = Mapcode.decode(mapcode, mapcodeTerritory);
LOG.info("Mapcode {} in territory {} represents latitude {} , longitude {}",
mapcode, mapcodeTerritory, p.getLatDeg(), p.getLonDeg());
}
catch (final UnknownMapcodeException ignored) {
LOG.info("Mapcode {} in territory {} is invalid", mapcode, mapcodeTerritory);
}
mapcode = "49.4A";
try {
final Point p = Mapcode.decode(mapcode, mapcodeTerritory);
LOG.info("Mapcode {} in territory {} represents latitude {} , longitude {}",
mapcode, mapcodeTerritory, p.getLatDeg(), p.getLonDeg());
}
catch (final UnknownMapcodeException ignored) {
LOG.info("Mapcode {} in territory {} is invalid", mapcode, mapcodeTerritory);
}
LOG.info("");
// example 5 - Encode a coordinate in this territory.
LOG.info("Example 5 (Encode examples):");
double lat = 52.376514;
double lon = 4.908542;
// get all results, exclude "world"
List<MapcodeInfo> results = Mapcode.encode(lat, lon, mapcodeTerritory);
LOG.info("Point latitude {}, longitude {} has {} possible Mapcodes in {}",
lat, lon, results.size(), mapcodeTerritory.getFullName());
int count = 1;
for (final MapcodeInfo result : results) {
final String result_mapcode = result.getMapcode();
final int resultCcode = result.getTerritory().getTerritoryCode();
// let's give non-earth Mapcodes an explicit, non-ambiguous territory prefix
String resultPrefix = "";
if (result_mapcode.length() != 10) {
resultPrefix =
Territory.fromTerritoryCode(resultCcode).toString(
Territory.TerritoryNameFormat.MINIMAL_UNAMBIGUOUS) + ' ';
}
LOG.info(" Alternative {}: {} {}", count, resultPrefix, result_mapcode);
++count;
}
LOG.info("");
// example 6 - Encode a coordinate in ALL possible territories.
LOG.info("Example 6:");
lat = 26.87016;
lon = 75.847;
LOG.info("All possible Mapcodes in the world for latitude {}, longitude {}", lat, lon);
results = Mapcode.encode(lat, lon);
count = 1;
for (final MapcodeInfo result : results) {
final String result_mapcode = result.getMapcode();
final int result_ccode = result.getTerritory().getTerritoryCode();
// let's give non-earth Mapcodes an explicit, non-ambiguous territory prefix
String result_prefix = "";
if (result_mapcode.length() != 10) {
result_prefix =
Territory.fromTerritoryCode(result_ccode).toString(
Territory.TerritoryNameFormat.MINIMAL_UNAMBIGUOUS) +
' ';
}
LOG.info(" Alternative {}: {} {}", count, result_prefix, result_mapcode);
++count;
}
}
}
|
package com.rcv;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.rcv.RawContestConfig.CVRSource;
import com.rcv.RawContestConfig.Candidate;
import com.rcv.RawContestConfig.ContestRules;
import com.rcv.RawContestConfig.OutputSettings;
import java.io.BufferedReader;
import java.io.File;
import java.io.InputStreamReader;
import java.net.URL;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Optional;
import java.util.ResourceBundle;
import java.util.logging.Level;
import java.util.stream.Collectors;
import javafx.application.Platform;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.collections.FXCollections;
import javafx.concurrent.Service;
import javafx.concurrent.Task;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Alert;
import javafx.scene.control.Alert.AlertType;
import javafx.scene.control.ButtonBar;
import javafx.scene.control.ButtonType;
import javafx.scene.control.ChoiceBox;
import javafx.scene.control.DatePicker;
import javafx.scene.control.Label;
import javafx.scene.control.RadioButton;
import javafx.scene.control.SelectionMode;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.TextArea;
import javafx.scene.control.TextField;
import javafx.scene.control.ToggleGroup;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.stage.DirectoryChooser;
import javafx.stage.FileChooser;
import javafx.stage.FileChooser.ExtensionFilter;
import javafx.util.StringConverter;
public class GuiConfigController implements Initializable {
private static final DateTimeFormatter DATE_TIME_FORMATTER =
DateTimeFormatter.ofPattern("yyyy-MM-dd");
private static final String CONFIG_FILE_NAME = "config_file_documentation.txt";
private String emptyConfigString;
// file selected for loading
private File selectedFile;
@FXML
private TextArea textAreaStatus;
@FXML
private TextArea textAreaHelp;
@FXML
private Label labelCurrentlyLoaded;
@FXML
private TextField textFieldContestName;
@FXML
private TextField textFieldOutputDirectory;
@FXML
private DatePicker datePickerContestDate;
@FXML
private TextField textFieldContestJurisdiction;
@FXML
private TextField textFieldContestOffice;
@FXML
private ToggleGroup toggleTabulateByPrecinct;
@FXML
private RadioButton radioTabulateByPrecinctTrue;
@FXML
private RadioButton radioTabulateByPrecinctFalse;
@FXML
private TableView<CVRSource> tableViewCvrFiles;
@FXML
private TableColumn<CVRSource, String> tableColumnCvrFilePath;
@FXML
private TableColumn<CVRSource, Integer> tableColumnCvrFirstVoteCol;
@FXML
private TableColumn<CVRSource, Integer> tableColumnCvrIdCol;
@FXML
private TableColumn<CVRSource, Integer> tableColumnCvrPrecinctCol;
@FXML
private TableColumn<CVRSource, String> tableColumnCvrProvider;
@FXML
private TextField textFieldCvrFilePath;
@FXML
private TextField textFieldCvrFirstVoteCol;
@FXML
private TextField textFieldCvrIdCol;
@FXML
private TextField textFieldCvrPrecinctCol;
@FXML
private TextField textFieldCvrProvider;
@FXML
private TableView<Candidate> tableViewCandidates;
@FXML
private TableColumn<Candidate, String> tableColumnCandidateName;
@FXML
private TableColumn<Candidate, String> tableColumnCandidateCode;
@FXML
private TextField textFieldCandidateName;
@FXML
private TextField textFieldCandidateCode;
@FXML
private ChoiceBox<Tabulator.TieBreakMode> choiceTiebreakMode;
@FXML
private ChoiceBox<Tabulator.OvervoteRule> choiceOvervoteRule;
@FXML
private TextField textFieldMaxRankingsAllowed;
@FXML
private TextField textFieldMaxSkippedRanksAllowed;
@FXML
private TextField textFieldNumberOfWinners;
@FXML
private TextField textFieldDecimalPlacesForVoteArithmetic;
@FXML
private TextField textFieldMinimumVoteThreshold;
@FXML
private TextField textFieldOvervoteLabel;
@FXML
private TextField textFieldUndervoteLabel;
@FXML
private TextField textFieldUndeclaredWriteInLabel;
@FXML
private TextField textFieldRulesDescription;
@FXML
private ToggleGroup toggleBatchElimination;
@FXML
private RadioButton radioBatchEliminationTrue;
@FXML
private RadioButton radioBatchEliminationFalse;
@FXML
private ToggleGroup toggleContinueUntilTwoCandidatesRemain;
@FXML
private RadioButton radioContinueUntilTwoCandidatesRemainTrue;
@FXML
private RadioButton radioContinueUntilTwoCandidatesRemainFalse;
@FXML
private ToggleGroup toggleExhaustOnDuplicateCandidate;
@FXML
private RadioButton radioExhaustOnDuplicateCandidateTrue;
@FXML
private RadioButton radioExhaustOnDuplicateCandidateFalse;
@FXML
private ToggleGroup toggleTreatBlankAsUndeclaredWriteIn;
@FXML
private RadioButton radioTreatBlankAsUndeclaredWriteInTrue;
@FXML
private RadioButton radioTreatBlankAsUndeclaredWriteInFalse;
@FXML
private ButtonBar buttonBar;
public void buttonNewConfigClicked() {
if (checkForSaveAndContinue()) {
Logger.log(Level.INFO, "Creating new config.");
GuiContext.getInstance().setConfig(null);
selectedFile = null;
clearConfig();
}
}
public void buttonLoadConfigClicked() {
if (checkForSaveAndContinue()) {
FileChooser fc = new FileChooser();
if (selectedFile == null) {
fc.setInitialDirectory(new File(System.getProperty("user.dir")));
} else {
fc.setInitialDirectory(new File(selectedFile.getParent()));
}
fc.getExtensionFilters().add(new ExtensionFilter("JSON files", "*.json"));
fc.setTitle("Load Config");
selectedFile = fc.showOpenDialog(null);
if (selectedFile != null) {
GuiContext.getInstance().setConfig(Main.loadContestConfig(selectedFile.getAbsolutePath()));
if (GuiContext.getInstance().getConfig() != null) {
loadConfig(GuiContext.getInstance().getConfig());
labelCurrentlyLoaded.setText("Currently loaded: " + selectedFile.getAbsolutePath());
}
}
}
}
private File getSaveFile() {
FileChooser fc = new FileChooser();
if (selectedFile == null) {
fc.setInitialDirectory(new File(System.getProperty("user.dir")));
} else {
fc.setInitialDirectory(new File(selectedFile.getParent()));
fc.setInitialFileName(selectedFile.getName());
}
fc.getExtensionFilters().add(new ExtensionFilter("JSON files", "*.json"));
fc.setTitle("Save Config");
return fc.showSaveDialog(null);
}
private void saveFile(File saveFile) {
RawContestConfig rawConfig = createRawContestConfig();
JsonParser.createFileFromRawContestConfig(saveFile, rawConfig);
GuiContext.getInstance().setConfig(new ContestConfig(rawConfig));
labelCurrentlyLoaded.setText("Currently loaded: " + saveFile.getAbsolutePath());
}
public void buttonSaveClicked() {
File saveFile = getSaveFile();
if (saveFile != null) {
saveFile(saveFile);
}
}
public void buttonValidateClicked() {
buttonBar.setDisable(true);
ValidatorService service = new ValidatorService(createRawContestConfig());
service.setOnSucceeded(event -> buttonBar.setDisable(false));
service.setOnCancelled(event -> buttonBar.setDisable(false));
service.setOnFailed(event -> buttonBar.setDisable(false));
service.start();
}
public void buttonTabulateClicked() {
// TODO: customize message box so there's no "no"
if (checkForSaveAndContinue()) {
if (GuiContext.getInstance().getConfig() != null) {
buttonBar.setDisable(true);
TabulatorService service = new TabulatorService();
service.setOnSucceeded(event -> buttonBar.setDisable(false));
service.setOnCancelled(event -> buttonBar.setDisable(false));
service.setOnFailed(event -> buttonBar.setDisable(false));
service.start();
} else {
Logger.log(Level.WARNING, "Please load a config file before attempting to tabulate!");
}
}
}
public void buttonExitClicked() {
if (checkForSaveAndContinue()) {
Logger.log(Level.INFO, "Exiting tabulator GUI.");
Platform.exit();
}
}
public void buttonOutputDirectoryClicked() {
DirectoryChooser dc = new DirectoryChooser();
dc.setInitialDirectory(new File(System.getProperty("user.dir")));
dc.setTitle("Output Directory");
File outputDirectory = dc.showDialog(null);
if (outputDirectory != null) {
textFieldOutputDirectory.setText(outputDirectory.getAbsolutePath());
}
}
public void buttonClearDatePickerContestDateClicked() {
datePickerContestDate.setValue(null);
}
public void buttonCvrFilePathClicked() {
FileChooser fc = new FileChooser();
fc.setInitialDirectory(new File(System.getProperty("user.dir")));
fc.getExtensionFilters().add(new ExtensionFilter("Excel files", "*.xls", "*.xlsx"));
fc.setTitle("Select CVR File");
File openFile = fc.showOpenDialog(null);
if (openFile != null) {
textFieldCvrFilePath.setText(openFile.getAbsolutePath());
}
}
public void buttonAddCvrFileClicked() {
CVRSource cvrSource = new CVRSource();
if (textFieldCvrFilePath.getText().isEmpty()) {
Logger.log(Level.WARNING, "CVR file path is required!");
} else if (textFieldCvrFirstVoteCol.getText().isEmpty()) {
Logger.log(Level.WARNING, "CVR first vote column is required!");
} else {
cvrSource.setFilePath(textFieldCvrFilePath.getText());
cvrSource.setFirstVoteColumnIndex(getIntValueElse(textFieldCvrFirstVoteCol, null));
cvrSource.setIdColumnIndex(getIntValueElse(textFieldCvrIdCol, null));
cvrSource.setPrecinctColumnIndex(getIntValueElse(textFieldCvrPrecinctCol, null));
cvrSource.setProvider(textFieldCvrProvider.getText());
tableViewCvrFiles.getItems().add(cvrSource);
textFieldCvrFilePath.clear();
textFieldCvrFirstVoteCol.clear();
textFieldCvrIdCol.clear();
textFieldCvrPrecinctCol.clear();
textFieldCvrProvider.clear();
}
}
public void buttonDeleteCvrFileClicked() {
tableViewCvrFiles
.getItems()
.removeAll(tableViewCvrFiles.getSelectionModel().getSelectedItems());
}
public void buttonAddCandidateClicked() {
Candidate candidate = new Candidate();
if (textFieldCandidateName.getText().isEmpty()) {
Logger.log(Level.WARNING, "Candidate name field is required!");
} else {
candidate.setName(textFieldCandidateName.getText());
candidate.setCode(textFieldCandidateCode.getText());
tableViewCandidates.getItems().add(candidate);
textFieldCandidateName.clear();
textFieldCandidateCode.clear();
}
}
public void buttonDeleteCandidateClicked() {
tableViewCandidates
.getItems()
.removeAll(tableViewCandidates.getSelectionModel().getSelectedItems());
}
@Override
public void initialize(URL location, ResourceBundle resources) {
Logger.addGuiLogging(this.textAreaStatus);
Logger.log(Level.INFO, "Opening tabulator GUI.");
String helpText;
try {
helpText =
new BufferedReader(
new InputStreamReader(ClassLoader.getSystemResourceAsStream(CONFIG_FILE_NAME)))
.lines()
.collect(Collectors.joining("\n"));
} catch (Exception exception) {
Logger.log(Level.SEVERE, "Error loading: %s\n%s", CONFIG_FILE_NAME, exception.toString());
helpText = String.format("<Error loading %s>", CONFIG_FILE_NAME);
}
textAreaHelp.setText(helpText);
datePickerContestDate.setConverter(
new StringConverter<>() {
@Override
public String toString(LocalDate date) {
return date != null ? DATE_TIME_FORMATTER.format(date) : "";
}
@Override
public LocalDate fromString(String string) {
return string != null && !string.isEmpty()
? LocalDate.parse(string, DATE_TIME_FORMATTER)
: null;
}
});
textFieldCvrFirstVoteCol
.textProperty()
.addListener(new TextFieldListenerNonNegInt(textFieldCvrFirstVoteCol));
textFieldCvrIdCol.textProperty().addListener(new TextFieldListenerNonNegInt(textFieldCvrIdCol));
textFieldCvrPrecinctCol
.textProperty()
.addListener(new TextFieldListenerNonNegInt(textFieldCvrPrecinctCol));
tableColumnCvrFilePath.setCellValueFactory(new PropertyValueFactory<>("filePath"));
tableColumnCvrFirstVoteCol.setCellValueFactory(
new PropertyValueFactory<>("firstVoteColumnIndex"));
tableColumnCvrIdCol.setCellValueFactory(new PropertyValueFactory<>("idColumnIndex"));
tableColumnCvrPrecinctCol.setCellValueFactory(
new PropertyValueFactory<>("precinctColumnIndex"));
tableColumnCvrProvider.setCellValueFactory(new PropertyValueFactory<>("provider"));
tableViewCvrFiles.getSelectionModel().setSelectionMode(SelectionMode.MULTIPLE);
tableColumnCandidateName.setCellValueFactory(new PropertyValueFactory<>("name"));
tableColumnCandidateCode.setCellValueFactory(new PropertyValueFactory<>("code"));
tableViewCandidates.getSelectionModel().setSelectionMode(SelectionMode.MULTIPLE);
choiceTiebreakMode.getItems().addAll(Tabulator.TieBreakMode.values());
choiceTiebreakMode.getItems().remove(Tabulator.TieBreakMode.MODE_UNKNOWN);
choiceOvervoteRule.getItems().addAll(Tabulator.OvervoteRule.values());
choiceOvervoteRule.getItems().remove(Tabulator.OvervoteRule.RULE_UNKNOWN);
textFieldMaxRankingsAllowed
.textProperty()
.addListener(new TextFieldListenerNonNegInt(textFieldMaxRankingsAllowed));
textFieldMaxSkippedRanksAllowed
.textProperty()
.addListener(new TextFieldListenerNonNegInt(textFieldMaxSkippedRanksAllowed));
textFieldNumberOfWinners
.textProperty()
.addListener(new TextFieldListenerNonNegInt(textFieldNumberOfWinners));
textFieldDecimalPlacesForVoteArithmetic
.textProperty()
.addListener(new TextFieldListenerNonNegInt(textFieldDecimalPlacesForVoteArithmetic));
textFieldMinimumVoteThreshold
.textProperty()
.addListener(new TextFieldListenerNonNegInt(textFieldMinimumVoteThreshold));
setDefaultValues();
try {
emptyConfigString =
new ObjectMapper()
.writer()
.withDefaultPrettyPrinter()
.writeValueAsString(createRawContestConfig());
} catch (JsonProcessingException exception) {
Logger.log(
Level.WARNING,
"Unable to set emptyConfigString, but everything should work fine anyway!\n%s",
exception.toString());
}
}
private void setTextFieldToInteger(TextField textField, Integer value) {
if (value != null) {
textField.setText(Integer.toString(value));
}
}
private void setDefaultValues() {
labelCurrentlyLoaded.setText("Currently loaded: <new config>");
setToggleBoolean(
ContestConfig.DEFAULT_TABULATE_BY_PRECINCT,
radioTabulateByPrecinctTrue,
radioTabulateByPrecinctFalse);
setToggleBoolean(
ContestConfig.DEFAULT_BATCH_ELIMINATION,
radioBatchEliminationTrue,
radioBatchEliminationFalse);
setToggleBoolean(
ContestConfig.DEFAULT_EXHAUST_ON_DUPLICATE_CANDIDATES,
radioExhaustOnDuplicateCandidateTrue,
radioExhaustOnDuplicateCandidateFalse);
setToggleBoolean(
ContestConfig.DEFAULT_CONTINUE_UNTIL_TWO_CANDIDATES_REMAIN,
radioContinueUntilTwoCandidatesRemainTrue,
radioContinueUntilTwoCandidatesRemainFalse);
setToggleBoolean(
ContestConfig.DEFAULT_TREAT_BLANK_AS_UNDECLARED_WRITE_IN,
radioTreatBlankAsUndeclaredWriteInTrue,
radioTreatBlankAsUndeclaredWriteInFalse);
textFieldNumberOfWinners.setText(String.valueOf(ContestConfig.DEFAULT_NUMBER_OF_WINNERS));
textFieldDecimalPlacesForVoteArithmetic.setText(
String.valueOf(ContestConfig.DEFAULT_DECIMAL_PLACES_FOR_VOTE_ARITHMETIC));
textFieldMinimumVoteThreshold.setText(
String.valueOf(ContestConfig.DEFAULT_MINIMUM_VOTE_THRESHOLD));
}
private void clearConfig() {
textFieldContestName.clear();
textFieldOutputDirectory.clear();
datePickerContestDate.setValue(null);
textFieldContestJurisdiction.clear();
textFieldContestOffice.clear();
toggleTabulateByPrecinct.selectToggle(null);
textFieldCvrFilePath.clear();
textFieldCvrFirstVoteCol.clear();
textFieldCvrIdCol.clear();
textFieldCvrPrecinctCol.clear();
textFieldCvrProvider.clear();
tableViewCvrFiles.getItems().clear();
textFieldCandidateName.clear();
textFieldCandidateCode.clear();
tableViewCandidates.getItems().clear();
choiceTiebreakMode.setValue(null);
choiceOvervoteRule.setValue(null);
textFieldMaxRankingsAllowed.clear();
textFieldMaxSkippedRanksAllowed.clear();
textFieldNumberOfWinners.clear();
textFieldDecimalPlacesForVoteArithmetic.clear();
textFieldMinimumVoteThreshold.clear();
textFieldOvervoteLabel.clear();
textFieldUndervoteLabel.clear();
textFieldUndeclaredWriteInLabel.clear();
textFieldRulesDescription.clear();
toggleBatchElimination.selectToggle(null);
toggleContinueUntilTwoCandidatesRemain.selectToggle(null);
toggleExhaustOnDuplicateCandidate.selectToggle(null);
toggleTreatBlankAsUndeclaredWriteIn.selectToggle(null);
setDefaultValues();
}
private boolean checkForSaveAndContinue() {
boolean willContinue = false;
boolean needsSaving = true;
try {
String currentConfigString =
new ObjectMapper()
.writer()
.withDefaultPrettyPrinter()
.writeValueAsString(createRawContestConfig());
if (currentConfigString.equals(emptyConfigString)) {
// All fields are currently empty / default values so no point in asking to save
needsSaving = false;
} else if (GuiContext.getInstance().getConfig() != null) {
String savedConfigString =
new ObjectMapper()
.writer()
.withDefaultPrettyPrinter()
.writeValueAsString(GuiContext.getInstance().getConfig().rawConfig);
needsSaving = !currentConfigString.equals(savedConfigString);
}
} catch (JsonProcessingException exception) {
Logger.log(
Level.WARNING,
"Unable tell if saving is necessary, but everything should work fine anyway! Prompting for save just in case...\n%s",
exception.toString());
}
if (!needsSaving) {
willContinue = true;
} else {
ButtonType saveButton = new ButtonType("Save", ButtonBar.ButtonData.YES);
ButtonType dontSaveButton = new ButtonType("Don't Save", ButtonBar.ButtonData.NO);
Alert alert =
new Alert(
AlertType.CONFIRMATION,
"Do you want to save your changes before continuing?",
saveButton,
dontSaveButton,
ButtonType.CANCEL);
alert.setHeaderText(null);
Optional<ButtonType> result = alert.showAndWait();
if (result.isPresent() && result.get() == saveButton) {
File saveFile = getSaveFile();
if (saveFile != null) {
saveFile(saveFile);
willContinue = true;
}
} else if (result.isPresent() && result.get() == dontSaveButton) {
willContinue = true;
}
}
return willContinue;
}
private void loadConfig(ContestConfig config) {
clearConfig();
textFieldContestName.setText(config.getContestName());
textFieldOutputDirectory.setText(config.getOutputDirectory());
if (config.getContestDate() != null && !config.getContestDate().isEmpty()) {
datePickerContestDate.setValue(LocalDate.parse(config.getContestDate(), DATE_TIME_FORMATTER));
}
textFieldContestJurisdiction.setText(config.getContestJurisdiction());
textFieldContestOffice.setText(config.getContestOffice());
setToggleBoolean(
config.isTabulateByPrecinctEnabled(),
radioTabulateByPrecinctTrue,
radioTabulateByPrecinctFalse);
if (config.rawConfig.cvrFileSources != null) {
tableViewCvrFiles.setItems(
FXCollections.observableArrayList(config.rawConfig.cvrFileSources));
}
if (config.rawConfig.candidates != null) {
tableViewCandidates.setItems(FXCollections.observableArrayList(config.rawConfig.candidates));
}
choiceTiebreakMode.setValue(config.getTiebreakMode());
choiceOvervoteRule.setValue(config.getOvervoteRule());
setTextFieldToInteger(textFieldMaxRankingsAllowed, config.getMaxRankingsAllowed());
setTextFieldToInteger(textFieldMaxSkippedRanksAllowed, config.getMaxSkippedRanksAllowed());
setTextFieldToInteger(textFieldNumberOfWinners, config.getNumberOfWinners());
setTextFieldToInteger(
textFieldDecimalPlacesForVoteArithmetic, config.getDecimalPlacesForVoteArithmetic());
setTextFieldToInteger(
textFieldMinimumVoteThreshold, config.getMinimumVoteThreshold().intValue());
textFieldOvervoteLabel.setText(config.getOvervoteLabel());
textFieldUndervoteLabel.setText(config.getUndervoteLabel());
textFieldUndeclaredWriteInLabel.setText(config.getUndeclaredWriteInLabel());
textFieldRulesDescription.setText(config.getRulesDescription());
setToggleBoolean(
config.isBatchEliminationEnabled(), radioBatchEliminationTrue, radioBatchEliminationFalse);
setToggleBoolean(
config.willContinueUntilTwoCandidatesRemain(),
radioContinueUntilTwoCandidatesRemainTrue,
radioContinueUntilTwoCandidatesRemainFalse);
setToggleBoolean(
config.isExhaustOnDuplicateCandidateEnabled(),
radioExhaustOnDuplicateCandidateTrue,
radioExhaustOnDuplicateCandidateFalse);
setToggleBoolean(
config.isTreatBlankAsUndeclaredWriteInEnabled(),
radioTreatBlankAsUndeclaredWriteInTrue,
radioTreatBlankAsUndeclaredWriteInFalse);
}
// TODO: this function assumes that if a field isn't provided in the config, it'll be false
private void setToggleBoolean(boolean condition, RadioButton radioTrue, RadioButton radioFalse) {
if (condition) {
radioTrue.setSelected(true);
} else {
radioFalse.setSelected(true);
}
}
private boolean getToggleBoolean(ToggleGroup toggleGroup) {
return ((RadioButton) toggleGroup.getSelectedToggle()).getText().equals("True");
}
private Integer getIntValueElse(TextField textField, Integer defaultValue) {
Integer returnValue;
try {
if (textField.getText().isEmpty()) {
throw new IllegalArgumentException();
}
returnValue = Integer.valueOf(textField.getText());
} catch (Exception exception) {
Logger.log(
Level.WARNING,
"Integer required! Illegal value '%s' was replaced by '%s'",
textField.getText(),
defaultValue);
returnValue = defaultValue;
}
return returnValue;
}
private String getChoiceElse(ChoiceBox choiceBox, Enum defaultValue) {
return choiceBox.getValue() != null ? choiceBox.getValue().toString() : defaultValue.toString();
}
private RawContestConfig createRawContestConfig() {
RawContestConfig config = new RawContestConfig();
OutputSettings outputSettings = new OutputSettings();
outputSettings.contestName = textFieldContestName.getText();
outputSettings.outputDirectory = textFieldOutputDirectory.getText();
outputSettings.contestDate =
datePickerContestDate.getValue() != null ? datePickerContestDate.getValue().toString() : "";
outputSettings.contestJurisdiction = textFieldContestJurisdiction.getText();
outputSettings.contestOffice = textFieldContestOffice.getText();
outputSettings.tabulateByPrecinct = getToggleBoolean(toggleTabulateByPrecinct);
config.outputSettings = outputSettings;
config.cvrFileSources = new ArrayList<>(tableViewCvrFiles.getItems());
config.candidates = new ArrayList<>(tableViewCandidates.getItems());
ContestRules rules = new ContestRules();
rules.tiebreakMode = getChoiceElse(choiceTiebreakMode, Tabulator.TieBreakMode.MODE_UNKNOWN);
rules.overvoteRule = getChoiceElse(choiceOvervoteRule, Tabulator.OvervoteRule.RULE_UNKNOWN);
rules.maxRankingsAllowed = getIntValueElse(textFieldMaxRankingsAllowed, null);
rules.maxSkippedRanksAllowed = getIntValueElse(textFieldMaxSkippedRanksAllowed, null);
rules.numberOfWinners =
getIntValueElse(textFieldNumberOfWinners, ContestConfig.DEFAULT_NUMBER_OF_WINNERS);
rules.decimalPlacesForVoteArithmetic =
getIntValueElse(
textFieldDecimalPlacesForVoteArithmetic,
ContestConfig.DEFAULT_DECIMAL_PLACES_FOR_VOTE_ARITHMETIC);
rules.minimumVoteThreshold =
getIntValueElse(
textFieldMinimumVoteThreshold, ContestConfig.DEFAULT_MINIMUM_VOTE_THRESHOLD.intValue());
rules.batchElimination = getToggleBoolean(toggleBatchElimination);
rules.continueUntilTwoCandidatesRemain =
getToggleBoolean(toggleContinueUntilTwoCandidatesRemain);
rules.exhaustOnDuplicateCandidate = getToggleBoolean(toggleExhaustOnDuplicateCandidate);
rules.treatBlankAsUndeclaredWriteIn = getToggleBoolean(toggleTreatBlankAsUndeclaredWriteIn);
rules.overvoteLabel = textFieldOvervoteLabel.getText();
rules.undervoteLabel = textFieldUndervoteLabel.getText();
rules.undeclaredWriteInLabel = textFieldUndeclaredWriteInLabel.getText();
rules.rulesDescription = textFieldRulesDescription.getText();
config.rules = rules;
return config;
}
private static class ValidatorService extends Service<Void> {
private final RawContestConfig rawContestConfig;
ValidatorService(RawContestConfig rawContestConfig) {
this.rawContestConfig = rawContestConfig;
}
@Override
protected Task<Void> createTask() {
return new Task<>() {
@Override
protected Void call() {
new ContestConfig(rawContestConfig).validate();
return null;
}
};
}
}
private static class TabulatorService extends Service<Void> {
@Override
protected Task<Void> createTask() {
return new Task<>() {
@Override
protected Void call() {
Main.executeTabulation(GuiContext.getInstance().getConfig());
return null;
}
};
}
}
private class TextFieldListenerNonNegInt implements ChangeListener<String> {
// Restricts text fields to non-negative integers
private final TextField textField;
TextFieldListenerNonNegInt(TextField textField) {
this.textField = textField;
}
@Override
public void changed(
ObservableValue<? extends String> observable, String oldValue, String newValue) {
if (!newValue.matches("\\d*")) {
textField.setText(oldValue);
}
}
}
}
|
package com.transparentdiscord;
import com.transparentdiscord.UI.*;
import net.dv8tion.jda.client.entities.Group;
import net.dv8tion.jda.core.AccountType;
import net.dv8tion.jda.core.JDA;
import net.dv8tion.jda.core.JDABuilder;
import net.dv8tion.jda.core.entities.*;
import net.dv8tion.jda.core.exceptions.RateLimitedException;
import javax.imageio.ImageIO;
import javax.security.auth.login.LoginException;
import javax.swing.*;
import java.awt.*;
import java.awt.event.FocusAdapter;
import java.awt.event.FocusEvent;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.*;
import java.util.List;
public class Main {
public static List<Guild> guilds; //A list of what Discord calls "servers" (henceforth these will be referred to as guilds
public static List<PrivateChannel> privateChannels; //A list of Private/Direct Messages
public static List<TextChannel> textChannels; //A list of text channels from Guilds/Servers
public static HashMap<String, UIChat> chatWindows; //Maps the ID of a MessageChannel (String) to the UI associated with that channel (UIChat)
public static JFrame channelWindow; //The JFrame responsible for displaying a UIChannelList
public static JFrame chatWindow; //The JFrame responsible for displaying the active UIChat
public static JFrame bubbleWindow; //The JFrame responsible for displaying the chat bubbles
public static JPanel bubblePane; //The JPanel that contains the chat bubbles
private static GridBagConstraints gbc; //Constraints for adding bubbles to bubblePane
private static HashMap<String, ImageIcon> chatIcons; //Maps the ID of a chat, guild, or user icon to the icon
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String token = scanner.nextLine(); //Read the user token (obtainable from the Discord web client). Used to log in.
chatWindows = new HashMap<>();
chatIcons = new HashMap<>();
try {
JDA jda = new JDABuilder(AccountType.CLIENT) //Initialize the API
.setToken(token) //Log in with the token specified on stdin
.addEventListener(new MessageListenerTest()) //Add a message listener to handle Discord events (messages, calls, etc.)
.buildBlocking(); //Makes sure the API finishes initializing before continuing (as opposed to buildAsync()
guilds = jda.getGuilds(); //Get a list of all the guilds the user is a member of
privateChannels = jda.getPrivateChannels(); //Get a list of all the user's private chats (note: these are chats the user has already created, not one for every contact/friend)
textChannels = jda.getTextChannels(); //Get a list of all the text chats from the user's guilds
channelWindow = new JFrame();
channelWindow.setUndecorated(true); //Remove the window border
channelWindow.setSize(300,500);
chatWindow = new JFrame();
chatWindow.setUndecorated(true);
chatWindow.setSize(300,500);
chatWindow.addFocusListener(new FocusAdapter() {
@Override
public void focusLost(FocusEvent focusEvent) {
super.focusLost(focusEvent);
chatWindow.setVisible(false);
}
});
bubbleWindow = new JFrame();
bubbleWindow.setLocationRelativeTo(null);
bubbleWindow.setUndecorated(true);
bubbleWindow.setBackground(new Color(0,0,0,0));//Make the window transparent
bubbleWindow.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //Kill the program if the bubble window is closed
bubblePane = new JPanel();
bubblePane.setLayout(new GridBagLayout());
bubblePane.setBackground(new Color(0,0,0,0));
gbc = new GridBagConstraints();
gbc.gridwidth = GridBagConstraints.REMAINDER;
gbc.weightx = 1;
// gbc.ipady = 45;
gbc.fill = GridBagConstraints.HORIZONTAL;
bubblePane.add(new UIFloatingButton(bubbleWindow, channelWindow), gbc, 0); //Add the channel list button
bubbleWindow.add(bubblePane);
bubbleWindow.setSize(50,50);
bubbleWindow.setVisible(true);
UIChannelList channelList = new UIChannelList();
channelList.addGuilds(guilds);
channelList.addPrivateChannels(privateChannels);
channelWindow.add(channelList); //Add a channel list, currently only containing private channels, the the channel window
//TODO add Groups and Guild Text Channels to the channel list (see UIChannelList)
} catch (InterruptedException e) {
e.printStackTrace();
} catch (RateLimitedException e) {
e.printStackTrace();
} catch (LoginException e) {
e.printStackTrace();
}
}
/**
* Repositions chatWindow and channelWindow relative to the bubbles
*/
public static void repositionWindows() {
int bubbleX = bubbleWindow.getX();
int bubbleY = bubbleWindow.getY();
chatWindow.setLocation(bubbleX-305,bubbleY-(500-bubbleWindow.getHeight()));
channelWindow.setLocation(bubbleX-305,bubbleY-(500-bubbleWindow.getHeight()));
}
/**
* Given a channel, opens a UIChat inside chatWindow with that channel, either retrieving
* it from chatWindows or initializing a new one
* @param channel the channel to open
*/
public static void openChat(MessageChannel channel) {
if (channel instanceof PrivateChannel) { //If the channel is a private channel...
UIPrivateChat pc;
if (chatWindows.containsKey(channel.getId())) //If the channel has already been opened...
pc = (UIPrivateChat) chatWindows.get(channel.getId()); //Retrieve the UIChat object from chatWindows
else {
pc = new UIPrivateChat((PrivateChannel) channel); //Otherwise, create a new UIChat
chatWindows.put(channel.getId(), pc); //Put it in chatWindows
addBubble(pc.getChannel(), getImage((PrivateChannel) channel));//And add a bubble for it
}
chatWindow.getContentPane().removeAll(); //Clear the chatWindow, removing any previously opened chats
chatWindow.add(pc); //Add the new UIChat
chatWindow.revalidate();
chatWindow.repaint(); //Reload the chatWindow
chatWindow.setVisible(true); //Make sure chatWindow is displayed
channelWindow.setVisible(false); //Hide the channel list
}
}
/**
* Adds a bubble to the bubble list for a given channel
* Clicking the button will open the given channel inside a UIChat inside chatWindow
* @param channel the channel to add a bubble for
*/
public static void addBubble(MessageChannel channel, ImageIcon imageIcon) {
bubblePane.add(new UIFloatingButton(channel, imageIcon), gbc, 0);
bubblePane.revalidate();
bubblePane.repaint();
resizeBubbles();
repositionWindows();
}
/**
* Resizes the bubble window to appropriately fit the current number of bubbles
*/
private static void resizeBubbles() {
//TODO switch to more specific, less esoteric math (use variables to set bubble size, etc.)
bubbleWindow.setLocation(bubbleWindow.getX(), bubbleWindow.getY() - 50); //Move the bubbles down 50 pixels (the size of a bubble)
bubbleWindow.setSize(50,bubblePane.getComponentCount()*65); //Increase the size of the bubble container
bubbleWindow.revalidate();
bubbleWindow.repaint();
}
public static ImageIcon getImage(Guild guild) {
if (chatIcons.containsKey(guild.getIconId()))
return chatIcons.get(guild.getIconId());
else {
try {
ImageIcon image = getImageFromURL(new URL(guild.getIconUrl()));
chatIcons.put(guild.getIconId(), image);
return image;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
public static ImageIcon getImage(Group group) {
if (chatIcons.containsKey(group.getIconId()))
return chatIcons.get(group.getIconId());
else {
try {
ImageIcon image = getImageFromURL(new URL(group.getIconUrl()));
chatIcons.put(group.getIconId(), image);
return image;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
public static ImageIcon getImage(PrivateChannel privateChannel) {
return getImage(privateChannel.getUser());
}
public static ImageIcon getImage(User user) {
if (chatIcons.containsKey(user.getAvatarId()))
return chatIcons.get(user.getAvatarId());
else {
try {
ImageIcon image = getCircularImageFromURL(new URL(user.getAvatarUrl()));
chatIcons.put(user.getAvatarId(), image);
return image;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
public static ImageIcon getImage(User user, int width, int height) {
Image image = getImage(user).getImage();
image = image.getScaledInstance(width,height,Image.SCALE_SMOOTH);
return new ImageIcon(image);
}
public static ImageIcon getImageFromURL(URL url) throws IOException {
final HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestProperty(
"User-Agent",
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_5) AppleWebKit/537.31 (KHTML, like Gecko) Chrome/26.0.1410.65 Safari/537.31");
final BufferedImage image = ImageIO.read(connection.getInputStream());
return new ImageIcon(image);
}
public static ImageIcon getCircularImageFromURL(URL url) throws IOException {
final HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestProperty(
"User-Agent",
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_5) AppleWebKit/537.31 (KHTML, like Gecko) Chrome/26.0.1410.65 Safari/537.31");
final BufferedImage image = ImageIO.read(connection.getInputStream());
return new ImageIcon(clipToCircle(image));
}
public static ImageIcon resizeToWidth(ImageIcon image, int width) {
float ratio = (float) image.getIconHeight()/image.getIconWidth();
int height = (int) (ratio * width);
return new ImageIcon(image.getImage().getScaledInstance(width,height,Image.SCALE_SMOOTH));
}
private static BufferedImage clipToCircle(BufferedImage image) {
int diameter = Math.min(image.getWidth(), image.getHeight());
BufferedImage mask = new BufferedImage(image.getWidth(), image.getHeight(), BufferedImage.TYPE_INT_ARGB);
Graphics2D g2d = mask.createGraphics();
applyRenderingHints(g2d);
g2d.fillOval(0, 0, diameter - 1, diameter - 1);
g2d.dispose();
BufferedImage masked = new BufferedImage(diameter, diameter, BufferedImage.TYPE_INT_ARGB);
g2d = masked.createGraphics();
applyRenderingHints(g2d);
int x = (diameter - image.getWidth()) / 2;
int y = (diameter - image.getHeight()) / 2;
g2d.drawImage(image, x, y, null);
g2d.setComposite(AlphaComposite.getInstance(AlphaComposite.DST_IN));
g2d.drawImage(mask, 0, 0, null);
g2d.dispose();
return masked;
}
private static void applyRenderingHints(Graphics2D g2d) {
g2d.setRenderingHint(RenderingHints.KEY_ALPHA_INTERPOLATION, RenderingHints.VALUE_ALPHA_INTERPOLATION_QUALITY);
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g2d.setRenderingHint(RenderingHints.KEY_COLOR_RENDERING, RenderingHints.VALUE_COLOR_RENDER_QUALITY);
g2d.setRenderingHint(RenderingHints.KEY_DITHERING, RenderingHints.VALUE_DITHER_ENABLE);
g2d.setRenderingHint(RenderingHints.KEY_FRACTIONALMETRICS, RenderingHints.VALUE_FRACTIONALMETRICS_ON);
g2d.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
g2d.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
g2d.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, RenderingHints.VALUE_STROKE_PURE);
}
public static int getChatWidth() {
return chatWindow.getWidth();
}
}
|
package com.venky.geo;
import java.math.BigDecimal;
public class GeoCoordinate implements GeoLocation{
private double latInRadians;
private double lngInRadians;
private static final double R = 6378.1370 ; //Equitorial Radius of Earth.
private GeoLocation inner ;
@Deprecated
/**
* deprecated use GeoCoordinate(GeoLocation ref) ;
* Kept for Serialization routines.
*/
public GeoCoordinate(){
}
public GeoCoordinate(GeoLocation ref){
setInner(ref);
}
public void setInner(GeoLocation inner){
this.inner = inner;
if (inner != null){
this.setLat(inner.getLat());
this.setLng(inner.getLng());
}
}
@SuppressWarnings("unchecked")
public <T extends GeoLocation> T inner(){
return (T)inner;
}
public GeoCoordinate(BigDecimal lat,BigDecimal lng){
setLat(lat);
setLng(lng);
}
public GeoCoordinate(double lat,double lng){
this(new BigDecimal(lat),new BigDecimal(lng));
}
public GeoCoordinate(Vector3d d3Vector){
double lng = Math.atan2(d3Vector.y, d3Vector.x);
double hyp = Math.sqrt(d3Vector.x * d3Vector.x + d3Vector.y * d3Vector.y );
double lat = Math.atan2(d3Vector.z , hyp);
this.latInRadians = lat;
this.lngInRadians = lng;
}
public BigDecimal getLat(){
return new BigDecimal(latInRadians * 180.0/Math.PI) ;
}
public BigDecimal getLng(){
return new BigDecimal(lngInRadians * 180.0/Math.PI) ;
}
public BigDecimal getLatInRadians(){
return new BigDecimal(latInRadians);
}
public BigDecimal getLngInRadians(){
return new BigDecimal(lngInRadians);
}
public void setLatInRadians(BigDecimal latInRadians){
this.latInRadians = latInRadians.doubleValue();
}
public void setLngInRadians(BigDecimal lngInRadians){
this.latInRadians = lngInRadians.doubleValue();
}
public Vector3d toVector(){
double x = R * Math.cos(latInRadians)*Math.cos(lngInRadians);
double y = R * Math.cos(latInRadians)*Math.sin(lngInRadians);
double z = R * Math.sin(latInRadians);
return new Vector3d(x,y,z);
}
public double distanceTo(GeoCoordinate another){
double dlat = (latInRadians - another.latInRadians);
double dlng = (lngInRadians - another.lngInRadians);
double a = Math.sin(dlat/2)* Math.sin(dlat/2) + Math.cos(latInRadians)*Math.cos(another.latInRadians) * Math.sin(dlng/2) * Math.sin(dlng/2);
return 2 * R * Math.asin(Math.min(1, Math.sqrt(a)));
}
public double distanceTo(GeoCoordinate start, GeoCoordinate end){
Vector3d gc = start.toVector().cross(end.toVector());
double angleBetweenThisAndGCVector = Math.abs(this.toVector().angle(gc)); // 0 to pi
double angleBetweenThisAndGCPlane = Math.abs((Math.PI/2) - angleBetweenThisAndGCVector) ;
return R * angleBetweenThisAndGCPlane;
}
@Override
public void setLat(BigDecimal latitude) {
latInRadians = latitude.doubleValue() * Math.PI/180.0 ;
}
@Override
public void setLng(BigDecimal longitude) {
lngInRadians = longitude.doubleValue() * Math.PI/ 180.0;
}
}
|
package de.ddb.pdc.metadata;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.GregorianCalendar;
/**
* Aggregates the metadata of an item from the DDB.
*/
public class DDBItem {
private String id;
private String title;
private String subtitle;
private String imageUrl;
private String media;
private String category;
private String type;
//metadata
private ArrayList<Author> authors = null;
private String institute = null;
private Calendar publishedYear = null;
/**
* Creates a new DDBItem.
*
* @param id item ID in the DDB database
*/
public DDBItem(String id) {
this.id = id;
this.authors = new ArrayList<Author>();
}
/**
* Returns the item ID assigned to the item by the DDB.
*/
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
/**
* Returns the title of the work represented by the item.
*/
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
/**
* Returns the subtitle (if any) of the work represented by the item.
* If the work has no subtitle, null is returned.
*/
public String getSubtitle() {
return subtitle;
}
public void setSubtitle(String subtitle) {
this.subtitle = subtitle;
}
/**
* Returns the URL of a thumbnail image that can be used when displaying
* the item in a user interface. The URL is always absolute.
*/
public String getImageUrl() {
return imageUrl;
}
public void setImageUrl(String imageUrl) {
this.imageUrl = imageUrl;
}
/**
* Returns the Media category of the work.
* If the work has no media, null is returned.
*/
public String getMedia() {
return media;
}
public void setMedia(String media) {
this.media = media;
}
/**
* Returns the category of the work.
* If the work has no category, null is returned.
*/
public String getCategory() {
return category;
}
public void setCategory(String category) {
this.category = category;
}
/**
* Returns the type of the work.
* If the work has no type, null is returned.
*/
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
/**
* Returns list of authors of the work.
* If no authors are found, null is returned.
*/
public ArrayList<Author> getAuthors() {
return authors;
}
public void addAuthor(Author author) {
this.authors.add(author);
}
/**
* Returns the institution which has the information about the work.
* If no institution found, null is returned.
*/
public String getInstitute() {
return institute;
}
public void setInstitute(String institute) {
this.institute = institute;
}
/**
* Returns the published year of the work.
* If no published year found, null is returned
*/
public Calendar getPublishedYear() {
return publishedYear;
}
public void setPublishedYear(int publishedYear) {
if (publishedYear != -1) {
this.publishedYear = new GregorianCalendar();
this.publishedYear.set(Calendar.YEAR, publishedYear);
}
}
}
|
package de.predic8.quartz;
import de.predic8.routes.DailyMailNotification;
import org.apache.camel.builder.RouteBuilder;
import org.springframework.stereotype.Component;
@Component
public class DailyMail extends RouteBuilder {
@Override
public void configure() throws Exception {
from("quartz2://notify?cron=0+0+21+?+*+*+*") // at 21:00 every day
//from("quartz2://notify?cron=0+*+*+?+*+*+*") // every minute
.routeId("Quartz: DailyMail")
.log("Start quartz/DailyMail Route")
.log("Sending daily mail...")
.process(exchange -> {
DailyMailNotification notify = new DailyMailNotification();
notify.start();
})
.log("End quartz/DailyMail Route");
}
}
|
package ee.shy.core.diff;
import ee.shy.core.Tree;
import ee.shy.core.TreeItem;
import ee.shy.storage.DataStorage;
import java.io.IOException;
import java.util.*;
public class TreeDiffer implements Differ<Tree> {
private final DataStorage storage;
public TreeDiffer(DataStorage storage) {
this.storage = storage;
}
@Override
public List<String> diff(Tree original, Tree revised) throws IOException {
List<String> diffStrings = new ArrayList<>();
Map<String, TreeItem> originalItems = original.getItems();
Map<String, TreeItem> revisedItems = revised.getItems();
Set<String> unionTreeKeySet = new HashSet<>();
unionTreeKeySet.addAll(originalItems.keySet());
unionTreeKeySet.addAll(revisedItems.keySet());
Map<ItemCase, ItemCaseHandler> itemCases = new HashMap<>();
itemCases.put(new ItemCase(TreeItem.Type.FILE, TreeItem.Type.FILE),
(originalItem, revisedItem) ->
new InputStreamDiffer().diff(storage.get(originalItem.getHash()), storage.get(revisedItem.getHash())));
for (String name : unionTreeKeySet) {
TreeItem originalItem = originalItems.get(name);
TreeItem revisedItem = revisedItems.get(name);
ItemCase itemCase = new ItemCase(
originalItem != null ? originalItem.getType() : null,
revisedItem != null ? revisedItem.getType() : null
);
ItemCaseHandler treeItemTreeItemListBiFunction = itemCases.get(itemCase);
if (treeItemTreeItemListBiFunction != null) {
List<String> singleDiffStrings = treeItemTreeItemListBiFunction.handle(originalItem, revisedItem);
diffStrings.addAll(singleDiffStrings);
}
}
return diffStrings;
}
private static class ItemCase {
private final TreeItem.Type originalType;
private final TreeItem.Type revisedType;
private ItemCase(TreeItem.Type originalType, TreeItem.Type revisedType) {
this.originalType = originalType;
this.revisedType = revisedType;
}
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (o == null || getClass() != o.getClass())
return false;
ItemCase itemCase = (ItemCase) o;
if (originalType != itemCase.originalType)
return false;
return revisedType == itemCase.revisedType;
}
@Override
public int hashCode() {
int result = originalType != null ? originalType.hashCode() : 0;
result = 31 * result + (revisedType != null ? revisedType.hashCode() : 0);
return result;
}
}
private interface ItemCaseHandler {
List<String> handle(TreeItem original, TreeItem revised) throws IOException;
}
}
|
package graphql.language;
import graphql.AssertException;
import graphql.PublicApi;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.io.Writer;
import java.util.Arrays;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import static graphql.Assert.assertTrue;
import static java.lang.String.valueOf;
import static java.util.stream.Collectors.joining;
/**
* This can take graphql language AST and print it out as a string
*/
@SuppressWarnings("UnnecessaryLocalVariable")
@PublicApi
public class AstPrinter {
private final Map<Class<? extends Node>, NodePrinter<? extends Node>> printers = new LinkedHashMap<>();
private AstPrinter() {
printers.put(Argument.class, argument());
printers.put(ArrayValue.class, value());
printers.put(BooleanValue.class, value());
printers.put(NullValue.class, value());
printers.put(Directive.class, directive());
printers.put(DirectiveDefinition.class, directiveDefinition());
printers.put(DirectiveLocation.class, directiveLocation());
printers.put(Document.class, document());
printers.put(EnumTypeDefinition.class, enumTypeDefinition());
printers.put(EnumTypeExtensionDefinition.class, enumTypeExtensionDefinition());
printers.put(EnumValue.class, enumValue());
printers.put(EnumValueDefinition.class, enumValueDefinition());
printers.put(Field.class, field());
printers.put(FieldDefinition.class, fieldDefinition());
printers.put(FloatValue.class, value());
printers.put(FragmentDefinition.class, fragmentDefinition());
printers.put(FragmentSpread.class, fragmentSpread());
printers.put(InlineFragment.class, inlineFragment());
printers.put(InputObjectTypeDefinition.class, inputObjectTypeDefinition());
printers.put(InputObjectTypeExtensionDefinition.class, inputObjectTypeExtensionDefinition());
printers.put(InputValueDefinition.class, inputValueDefinition());
printers.put(InterfaceTypeDefinition.class, interfaceTypeDefinition());
printers.put(InterfaceTypeExtensionDefinition.class, interfaceTypeExtensionDefinition());
printers.put(IntValue.class, value());
printers.put(ListType.class, type());
printers.put(NonNullType.class, type());
printers.put(ObjectField.class, objectField());
printers.put(ObjectTypeDefinition.class, objectTypeDefinition());
printers.put(ObjectTypeExtensionDefinition.class, objectTypeExtensionDefinition());
printers.put(ObjectValue.class, value());
printers.put(OperationDefinition.class, operationDefinition());
printers.put(OperationTypeDefinition.class, operationTypeDefinition());
printers.put(ScalarTypeDefinition.class, scalarTypeDefinition());
printers.put(ScalarTypeExtensionDefinition.class, scalarTypeExtensionDefinition());
printers.put(SchemaDefinition.class, schemaDefinition());
printers.put(SelectionSet.class, selectionSet());
printers.put(StringValue.class, value());
printers.put(TypeName.class, type());
printers.put(UnionTypeDefinition.class, unionTypeDefinition());
printers.put(UnionTypeExtensionDefinition.class, unionTypeExtensionDefinition());
printers.put(VariableDefinition.class, variableDefinition());
printers.put(VariableReference.class, variableReference());
}
private NodePrinter<Argument> argument() {
return (out, node) -> out.printf("%s: %s", node.getName(), value(node.getValue()));
}
private NodePrinter<Document> document() {
return (out, node) -> out.printf("%s\n", join(node.getDefinitions(), "\n\n"));
}
private NodePrinter<Directive> directive() {
return (out, node) -> {
String arguments = wrap("(", join(node.getArguments(), ", "), ")");
out.printf("@%s%s", node.getName(), arguments);
};
}
private NodePrinter<DirectiveDefinition> directiveDefinition() {
return (out, node) -> {
String arguments = wrap("(", join(node.getInputValueDefinitions(), ", "), ")");
String locations = join(node.getDirectiveLocations(), " | ");
out.printf("directive @%s%s on %s", node.getName(), arguments, locations);
};
}
private NodePrinter<DirectiveLocation> directiveLocation() {
return (out, node) -> out.print(node.getName());
}
private NodePrinter<EnumTypeDefinition> enumTypeDefinition() {
return (out, node) -> {
out.printf("%s", comments(node));
out.printf("%s",
spaced(
"enum",
node.getName(),
directives(node.getDirectives()),
block(node.getEnumValueDefinitions())
));
};
}
private NodePrinter<EnumValue> enumValue() {
return (out, node) -> out.printf("%s", node.getName());
}
private NodePrinter<EnumValueDefinition> enumValueDefinition() {
return (out, node) -> {
out.printf("%s", comments(node));
out.printf("%s",
spaced(
node.getName(),
directives(node.getDirectives())
));
};
}
private NodePrinter<Field> field() {
return (out, node) -> {
String alias = wrap("", node.getAlias(), ": ");
String name = node.getName();
String arguments = wrap("(", join(node.getArguments(), ", "), ")");
String directives = directives(node.getDirectives());
String selectionSet = node(node.getSelectionSet());
out.printf("%s", spaced(
alias + name + arguments,
directives,
selectionSet
));
};
}
private NodePrinter<FieldDefinition> fieldDefinition() {
return (out, node) -> {
out.printf("%s", comments(node));
String args;
if (hasComments(node.getInputValueDefinitions())) {
args = join(node.getInputValueDefinitions(), "\n");
out.printf("%s", node.getName() +
wrap("(\n", args, "\n)") +
": " +
spaced(
type(node.getType()),
directives(node.getDirectives())
)
);
} else {
args = join(node.getInputValueDefinitions(), ", ");
out.printf("%s", node.getName() +
wrap("(", args, ")") +
": " +
spaced(
type(node.getType()),
directives(node.getDirectives())
)
);
}
};
}
private boolean hasComments(List<? extends Node> nodes) {
return nodes.stream().anyMatch(it -> it.getComments().size() > 0);
}
private NodePrinter<FragmentDefinition> fragmentDefinition() {
return (out, node) -> {
String name = node.getName();
String typeCondition = type(node.getTypeCondition());
String directives = directives(node.getDirectives());
String selectionSet = node(node.getSelectionSet());
out.printf("fragment %s on %s ", name, typeCondition);
out.printf("%s", directives + selectionSet);
};
}
private NodePrinter<FragmentSpread> fragmentSpread() {
return (out, node) -> {
String name = node.getName();
String directives = directives(node.getDirectives());
out.printf("...%s%s", name, directives);
};
}
private NodePrinter<InlineFragment> inlineFragment() {
return (out, node) -> {
String typeCondition = wrap("on ", type(node.getTypeCondition()), "");
String directives = directives(node.getDirectives());
String selectionSet = node(node.getSelectionSet());
out.printf("%s", comments(node));
out.printf("%s", spaced(
"...",
typeCondition,
directives,
selectionSet
));
};
}
private NodePrinter<InputObjectTypeDefinition> inputObjectTypeDefinition() {
return (out, node) -> {
out.printf("%s", comments(node));
out.printf("%s", spaced(
"input",
node.getName(),
directives(node.getDirectives()),
block(node.getInputValueDefinitions())
)
);
};
}
private NodePrinter<InputValueDefinition> inputValueDefinition() {
return (out, node) -> {
Value defaultValue = node.getDefaultValue();
out.printf("%s", comments(node));
out.printf("%s", spaced(
node.getName() + ": " + type(node.getType()),
wrap("= ", defaultValue, ""),
directives(node.getDirectives())
)
);
};
}
private NodePrinter<InterfaceTypeDefinition> interfaceTypeDefinition() {
return (out, node) -> {
out.printf("%s", comments(node));
out.printf("%s", spaced(
"interface",
node.getName(),
directives(node.getDirectives()),
block(node.getFieldDefinitions())
)
);
};
}
private NodePrinter<ObjectField> objectField() {
return (out, node) -> out.printf("%s : %s", node.getName(), value(node.getValue()));
}
private NodePrinter<OperationDefinition> operationDefinition() {
return (out, node) -> {
String op = node.getOperation().toString().toLowerCase();
String name = node.getName();
String varDefinitions = wrap("(", join(nvl(node.getVariableDefinitions()), ", "), ")");
String directives = directives(node.getDirectives());
String selectionSet = node(node.getSelectionSet());
// Anonymous queries with no directives or variable definitions can use
// the query short form.
if (isEmpty(name) && isEmpty(directives) && isEmpty(varDefinitions) && op.equals("QUERY")) {
out.printf("%s", selectionSet);
} else {
out.printf("%s", spaced(op, smooshed(name, varDefinitions), directives, selectionSet));
}
};
}
private NodePrinter<OperationTypeDefinition> operationTypeDefinition() {
return (out, node) -> out.printf("%s: %s", node.getName(), type(node.getType()));
}
private NodePrinter<ObjectTypeDefinition> objectTypeDefinition() {
return (out, node) -> {
out.printf("%s", comments(node));
out.printf("%s", spaced(
"type",
node.getName(),
wrap("implements ", join(node.getImplements(), " & "), ""),
directives(node.getDirectives()),
block(node.getFieldDefinitions())
));
};
}
private NodePrinter<SelectionSet> selectionSet() {
return (out, node) -> {
out.printf("%s", comments(node));
out.printf("%s", block(node.getSelections()));
};
}
private NodePrinter<ScalarTypeDefinition> scalarTypeDefinition() {
return (out, node) -> {
out.printf("%s", comments(node));
out.printf("%s", spaced(
"scalar",
node.getName(),
directives(node.getDirectives())));
};
}
private NodePrinter<SchemaDefinition> schemaDefinition() {
return (out, node) -> {
out.printf("%s", comments(node));
out.printf("%s", spaced(
"schema",
directives(node.getDirectives()),
block(node.getOperationTypeDefinitions())
));
};
}
private NodePrinter<Type> type() {
return (out, node) -> out.print(type(node));
}
private String type(Type type) {
if (type instanceof NonNullType) {
NonNullType inner = (NonNullType) type;
return wrap("", type(inner.getType()), "!");
} else if (type instanceof ListType) {
ListType inner = (ListType) type;
return wrap("[", type(inner.getType()), "]");
} else {
TypeName inner = (TypeName) type;
return inner.getName();
}
}
private NodePrinter<ObjectTypeExtensionDefinition> objectTypeExtensionDefinition() {
return (out, node) -> out.printf("extend %s", node(node, ObjectTypeDefinition.class));
}
private NodePrinter<EnumTypeExtensionDefinition> enumTypeExtensionDefinition() {
return (out, node) -> out.printf("extend %s", node(node, EnumTypeDefinition.class));
}
private NodePrinter<InterfaceTypeDefinition> interfaceTypeExtensionDefinition() {
return (out, node) -> out.printf("extend %s", node(node, InterfaceTypeDefinition.class));
}
private NodePrinter<UnionTypeExtensionDefinition> unionTypeExtensionDefinition() {
return (out, node) -> out.printf("extend %s", node(node, UnionTypeDefinition.class));
}
private NodePrinter<ScalarTypeExtensionDefinition> scalarTypeExtensionDefinition() {
return (out, node) -> out.printf("extend %s", node(node, ScalarTypeDefinition.class));
}
private NodePrinter<InputObjectTypeExtensionDefinition> inputObjectTypeExtensionDefinition() {
return (out, node) -> out.printf("extend %s", node(node, InputObjectTypeDefinition.class));
}
private NodePrinter<UnionTypeDefinition> unionTypeDefinition() {
return (out, node) -> {
out.printf("%s", comments(node));
out.printf("%s", spaced(
"union",
node.getName(),
directives(node.getDirectives()),
"= " + join(node.getMemberTypes(), " | ")
));
};
}
private NodePrinter<VariableDefinition> variableDefinition() {
return (out, node) -> out.printf("$%s: %s%s",
node.getName(),
type(node.getType()),
wrap(" = ", node.getDefaultValue(), "")
);
}
private NodePrinter<VariableReference> variableReference() {
return (out, node) -> out.printf("$%s", node.getName());
}
private String node(Node node) {
return node(node, null);
}
private String node(Node node, Class startClass) {
if (startClass != null) {
assertTrue(startClass.isInstance(node), "The starting class must be in the inherit tree");
}
StringWriter sw = new StringWriter();
PrintWriter out = new PrintWriter(sw);
NodePrinter<Node> printer = _findPrinter(node, startClass);
printer.print(out, node);
return sw.toString();
}
@SuppressWarnings("unchecked")
private <T extends Node> NodePrinter<T> _findPrinter(Node node) {
return _findPrinter(node, null);
}
private <T extends Node> NodePrinter<T> _findPrinter(Node node, Class startClass) {
if (node == null) {
return (out, type) -> {
};
}
Class clazz = startClass != null ? startClass : node.getClass();
while (clazz != Object.class) {
NodePrinter nodePrinter = printers.get(clazz);
if (nodePrinter != null) {
//noinspection unchecked
return nodePrinter;
}
clazz = clazz.getSuperclass();
}
throw new AssertException(String.format("We have a missing printer implementation for %s : report a bug!", clazz));
}
private <T> boolean isEmpty(List<T> list) {
return list == null || list.isEmpty();
}
private boolean isEmpty(String s) {
return s == null || s.trim().length() == 0;
}
private <T> List<T> nvl(List<T> list) {
return list != null ? list : Collections.emptyList();
}
private NodePrinter<Value> value() {
return (out, node) -> out.print(value(node));
}
private String value(Value value) {
if (value instanceof IntValue) {
return valueOf(((IntValue) value).getValue());
} else if (value instanceof FloatValue) {
return valueOf(((FloatValue) value).getValue());
} else if (value instanceof StringValue) {
return wrap("\"", valueOf(((StringValue) value).getValue()), "\"");
} else if (value instanceof EnumValue) {
return valueOf(((EnumValue) value).getName());
} else if (value instanceof BooleanValue) {
return valueOf(((BooleanValue) value).isValue());
} else if (value instanceof NullValue) {
return "null";
} else if (value instanceof ArrayValue) {
return "[" + join(((ArrayValue) value).getValues(), ", ") + "]";
} else if (value instanceof ObjectValue) {
return "{" + join(((ObjectValue) value).getObjectFields(), ", ") + "}";
} else if (value instanceof VariableReference) {
return "$" + ((VariableReference) value).getName();
}
return "";
}
private String comments(Node<?> node) {
List<Comment> comments = nvl(node.getComments());
if (isEmpty(comments)) {
return "";
}
String s = comments.stream().map(c -> "#" + c.getContent()).collect(joining("\n", "", "\n"));
return s;
}
private String directives(List<Directive> directives) {
return join(nvl(directives), " ");
}
private <T extends Node> String join(List<T> nodes, String delim) {
return join(nodes, delim, "", "");
}
@SuppressWarnings("SameParameterValue")
private <T extends Node> String join(List<T> nodes, String delim, String prefix, String suffix) {
String s = nvl(nodes).stream().map(this::node).collect(joining(delim, prefix, suffix));
return s;
}
private String spaced(String... args) {
return join(" ", args);
}
private String smooshed(String... args) {
return join("", args);
}
private String join(String delim, String... args) {
String s = Arrays.stream(args).filter(arg -> !isEmpty(arg)).collect(joining(delim));
return s;
}
String wrap(String start, String maybeString, String end) {
if (isEmpty(maybeString)) {
if (start.equals("\"") && end.equals("\"")) {
return "\"\"";
}
return "";
}
return start + maybeString + (!isEmpty(end) ? end : "");
}
private <T extends Node> String block(List<T> nodes) {
if (isEmpty(nodes)) {
return "{}";
}
return indent("{\n"
+ join(nodes, "\n"))
+ "\n}";
}
private String indent(String maybeString) {
if (isEmpty(maybeString)) {
return "";
}
maybeString = maybeString.replaceAll("\\n", "\n ");
return maybeString;
}
@SuppressWarnings("SameParameterValue")
String wrap(String start, Node maybeNode, String end) {
if (maybeNode == null) {
return "";
}
return start + node(maybeNode) + (isEmpty(end) ? "" : end);
}
/**
* This will pretty print the AST node in graphql language format
*
* @param node the AST node to print
*
* @return the printed node in graphql language format
*/
public static String printAst(Node node) {
StringWriter sw = new StringWriter();
printAst(sw, node);
return sw.toString();
}
/**
* This will print the Ast node in graphql language format.
* The format is derived from the pretty print version by replacing
* all newlines and indentations through single space.
*
* @param node the AST node to print
*
* @return the printed node in graphql language format
*/
public static String printAstCompact(Node node) {
StringWriter sw = new StringWriter();
printAst(sw, node);
return sw.toString().replaceAll("\\s+", " ").trim();
}
/**
* This will pretty print the AST node in graphql language format
*
* @param writer the place to put the output
* @param node the AST node to print
*/
public static void printAst(Writer writer, Node node) {
AstPrinter astPrinter = new AstPrinter();
NodePrinter<Node> printer = astPrinter._findPrinter(node);
printer.print(new PrintWriter(writer), node);
}
/**
* These print nodes into output writers
*
* @param <T> the type of node
*/
private interface NodePrinter<T extends Node> {
void print(PrintWriter out, T node);
}
}
|
package hudson.remoting;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;
import javax.annotation.CheckForNull;
/**
* Restricts what classes can be received through remoting.
*
* @author Kohsuke Kawaguchi
* @since 2.53
*/
public abstract class ClassFilter {
/**
* Property to set to <b>override</b> the blacklist used by {{@link #DEFAULT} with a different set.
* The location should point to a a file containing regular expressions (one per line) of classes to blacklist.
* If this property is set but the file can not be read the default blacklist will be used.
* @since 2.53.2
*/
public static final String FILE_OVERRIDE_LOCATION_PROPERTY = "hudson.remoting.ClassFilter.DEFAULTS_OVERRIDE_LOCATION";
private static final Logger LOGGER = Logger.getLogger(ClassFilter.class.getName());
protected boolean isBlacklisted(String name) {
return false;
}
protected boolean isBlacklisted(Class c) {
return false;
}
public final String check(String name) {
if (isBlacklisted(name))
throw new SecurityException("Rejected: " +name);
return name;
}
public final Class check(Class c) {
if (isBlacklisted(c))
throw new SecurityException("Rejected: " +c.getName());
return c;
}
private static final String[] DEFAULT_PATTERNS = {
"^bsh[.].*",
"^com[.]google[.]inject[.].*",
"^com[.]mchange[.]v2[.]c3p0[.].*",
"^com[.]sun[.]jndi[.].*",
"^com[.]sun[.]corba[.].*",
"^com[.]sun[.]javafx[.].*",
"^com[.]sun[.]org[.]apache[.]regex[.]internal[.].*",
"^java[.]awt[.].*",
"^java[.]rmi[.].*",
"^javax[.]management[.].*",
"^javax[.]naming[.].*",
"^javax[.]script[.].*",
"^javax[.]swing[.].*",
"^org[.]apache[.]commons[.]beanutils[.].*",
"^org[.]apache[.]commons[.]collections[.]functors[.].*",
"^org[.]apache[.]myfaces[.].*",
"^org[.]apache[.]wicket[.].*",
".*org[.]apache[.]xalan.*",
"^org[.]codehaus[.]groovy[.]runtime[.].*",
"^org[.]hibernate[.].*",
"^org[.]python[.].*",
"^org[.]springframework[.](?!(\\p{Alnum}+[.])*\\p{Alnum}*Exception$).*",
"^sun[.]rmi[.].*",
"^javax[.]imageio[.].*",
"^java[.]util[.]ServiceLoader$",
"^java[.]net[.]URLClassLoader$"
};
/**
* A set of sensible default filtering rules to apply,
* unless the context guarantees the trust between two channels.
*/
public static final ClassFilter DEFAULT;
static {
try {
DEFAULT = createDefaultInstance();
} catch (ClassFilterException ex) {
LOGGER.log(Level.SEVERE, "Default class filter cannot be initialized. Remoting will not start", ex);
throw new ExceptionInInitializerError(ex);
}
}
/**
* Adds an additional exclusion to {@link #DEFAULT}.
*
* Does nothing if the default list has already been customized via {@link #FILE_OVERRIDE_LOCATION_PROPERTY}.
* This API is not supposed to be used anywhere outside Jenkins core, calls for other sources may be rejected later.
* @param filter a regular expression for {@link Class#getName} which, if matched according to {@link Matcher#matches}, will blacklist the class
* @throws ClassFilterException Filter pattern cannot be applied.
* It means either unexpected processing error or rejection by the internal logic.
* @since 3.11
*/
public static void appendDefaultFilter(Pattern filter) throws ClassFilterException {
if (System.getProperty(FILE_OVERRIDE_LOCATION_PROPERTY) == null) {
((RegExpClassFilter) DEFAULT).add(filter.toString());
}
}
/**
* No filtering whatsoever.
*/
public static final ClassFilter NONE = new ClassFilter() {
};
/**
* The default filtering rules to apply, unless the context guarantees the trust between two channels. The defaults
* values provide for user specified overrides - see {@link #FILE_OVERRIDE_LOCATION_PROPERTY}.
*/
/*package*/ static ClassFilter createDefaultInstance() throws ClassFilterException {
try {
List<String> patternOverride = loadPatternOverride();
if (patternOverride != null) {
LOGGER.log(Level.FINE, "Using user specified overrides for class blacklisting");
return new RegExpClassFilter(patternOverride.toArray(new String[patternOverride.size()]));
} else {
LOGGER.log(Level.FINE, "Using default in built class blacklisting");
return new RegExpClassFilter(DEFAULT_PATTERNS);
}
}
catch (Error e) {
// when being used by something like XStream the actual cause gets swallowed
LOGGER.log(Level.SEVERE, "Failed to initialize the default class filter", e);
throw e;
}
}
@CheckForNull
private static List<String> loadPatternOverride() {
String prop = System.getProperty(FILE_OVERRIDE_LOCATION_PROPERTY);
if (prop==null) {
return null;
}
LOGGER.log(Level.FINE, "Attempting to load user provided overrides for ClassFiltering from ''{0}''.", prop);
File f = new File(prop);
if (!f.exists() || !f.canRead()) {
throw new Error("Could not load user provided overrides for ClassFiltering from as " + prop + " does not exist or is not readable.");
}
BufferedReader br = null;
try {
br = new BufferedReader(new InputStreamReader(new FileInputStream(prop), Charset.defaultCharset()));
ArrayList<String> patterns = new ArrayList<String>();
for (String line = br.readLine(); line != null; line = br.readLine()) {
try {
Pattern.compile(line);
patterns.add(line);
} catch (PatternSyntaxException pex) {
throw new Error("Error compiling blacklist expressions - '" + line + "' is not a valid regular expression.", pex);
}
}
return patterns;
} catch (IOException ex) {
throw new Error("Could not load user provided overrides for ClassFiltering from as "+prop+" does not exist or is not readable.",ex);
} finally {
if (br != null) {
try {
br.close();
} catch (IOException ioEx) {
LOGGER.log(Level.WARNING, "Failed to cleanly close input stream", ioEx);
}
}
}
}
/**
* A class that uses a given set of regular expression patterns to determine if the class is blacklisted.
*/
private static final class RegExpClassFilter extends ClassFilter {
/**
* Any regex that is {@code ^some[.]package[.]name[.].*} or {@code ^some\.package\.name\.*} is really just a
* {@link String#startsWith(String)} test and we can reduce CPU usage by performing that test explicitly as
* well as reduce GC pressure.
*/
private static final Pattern OPTIMIZE1 = Pattern.compile(
"^\\^(([\\p{L}_$][\\p{L}\\p{N}_$]*(\\.|\\[\\.\\])?)+)\\.\\*$");
/**
* Any regex that is {@code ^\Qsome.package.name\E.*} is really just a {@link String#startsWith(String)}
* test and we can reduce CPU usage by performing that test explicitly as well as reduce GC pressure.
*/
private static final Pattern OPTIMIZE2 = Pattern.compile("^\\^\\Q[^\\\\]+\\\\E\\.\\*$");
private final List<Object> blacklistPatterns;
RegExpClassFilter(String[] patterns) throws ClassFilterException {
blacklistPatterns = new ArrayList<>(patterns.length);
for (String pattern : patterns) {
add(pattern);
}
}
void add(String pattern) throws ClassFilterException {
if (OPTIMIZE1.matcher(pattern).matches()) {
// this is a simple startsWith test, no need to slow things down with a regex
blacklistPatterns.add(pattern.substring(1, pattern.length() - 2).replace("[.]", "."));
} else if (OPTIMIZE2.matcher(pattern).matches()) {
// this is a simple startsWith test, no need to slow things down with a regex
blacklistPatterns.add(pattern.substring(3, pattern.length() - 4));
} else {
final Pattern regex;
try {
regex = Pattern.compile(pattern);
} catch (PatternSyntaxException ex) {
throw new ClassFilterException("Cannot add RegExp class filter", ex);
}
blacklistPatterns.add(regex);
}
}
@Override
protected boolean isBlacklisted(String name) {
for (Object p : blacklistPatterns) {
if (p instanceof Pattern && ((Pattern)p).matcher(name).matches()) {
return true;
} else if (p instanceof String && name.startsWith((String)p)) {
return true;
}
}
return false;
}
/**
* Report the patterns that it's using to help users verify the use of custom filtering rule
* and inspect its content at runtime if necessary.
*/
@Override
public String toString() {
return blacklistPatterns.toString();
}
}
/**
* Class for propagating exceptions in {@link ClassFilter}.
* @since 3.11
*/
public static class ClassFilterException extends Exception {
@CheckForNull
final String pattern;
public ClassFilterException(String message, PatternSyntaxException ex) {
this(message, ex, ex.getPattern());
}
public ClassFilterException(String message, @CheckForNull String pattern) {
this(message, new IllegalStateException(message), pattern);
}
public ClassFilterException(String message, Throwable cause, @CheckForNull String pattern) {
super(message, cause);
this.pattern = pattern;
}
@CheckForNull
public String getPattern() {
return pattern;
}
@Override
public String getMessage() {
return super.getMessage() + ". Pattern: " + pattern;
}
}
}
|
package hudson.remoting;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;
import edu.umd.cs.findbugs.annotations.CheckForNull;
/**
* Restricts what classes can be received through remoting.
*
* @author Kohsuke Kawaguchi
* @since 2.53
*/
public abstract class ClassFilter {
/**
* Property to set to <b>override<b> the blacklist used by {{@link #DEFAULT} with a different set.
* The location should point to a a file containing regular expressions (one per line) of classes to blacklist.
* If this property is set but the file can not be read the default blacklist will be used.
*/
public static final String FILE_OVERRIDE_LOCATION_PROPERTY = "hudson.remoting.ClassFilter.DEFAULTS_OVERRIDE_LOCATION";
private static final Logger LOGGER = Logger.getLogger(ClassFilter.class.getName());
protected boolean isBlacklisted(String name) {
return false;
}
protected boolean isBlacklisted(Class c) {
return false;
}
public final String check(String name) {
if (isBlacklisted(name))
throw new SecurityException("Rejected: " +name);
return name;
}
public final Class check(Class c) {
if (isBlacklisted(c))
throw new SecurityException("Rejected: " +c.getName());
return c;
}
private static final String[] DEFAULT_PATTERNS = {
"^com[.]google[.]inject[.].*",
"^com[.]sun[.]jndi[.]rmi[.].*",
"^java[.]rmi[.].*",
"^org[.]apache[.]commons[.]beanutils[.].*",
"^org[.]apache[.]commons[.]collections[.]functors[.].*",
".*org[.]apache[.]xalan.*",
"^org[.]codehaus[.]groovy[.]runtime[.].*",
"^org[.]hibernate[.].*",
"^org[.]springframework[.].*",
"^sun[.]rmi[.].*",
};
/**
* A set of sensible default filtering rules to apply,
* unless the context guarantees the trust between two channels.
*/
public static final ClassFilter DEFAULT = createDefaultInstance();
/**
* No filtering whatsoever.
*/
public static final ClassFilter NONE = new ClassFilter() {
};
/**
* The default filtering rules to apply, unless the context guarantees the trust between two channels. The defaults
* values provide for user specified overrides - see {@link #FILE_OVERRIDE_LOCATION_PROPERTY}.
*/
/*package*/ static ClassFilter createDefaultInstance() {
List<Pattern> patternOverride = loadPatternOverride();
if (patternOverride != null) {
LOGGER.log(Level.FINE, "Using user specified overrides for class blacklisting");
return new RegExpClassFilter(patternOverride);
} else {
LOGGER.log(Level.FINE, "Using default in built class blacklisting");
return new RegExpClassFilter(DEFAULT_PATTERNS);
}
}
@CheckForNull
private static List<Pattern> loadPatternOverride() {
String prop = System.getProperty(FILE_OVERRIDE_LOCATION_PROPERTY);
if (prop==null) {
return null;
}
LOGGER.log(Level.FINE, "Attempting to load user provided overrides for ClassFiltering from ''{0}''.", prop);
File f = new File(prop);
if (!f.exists() || !f.canRead()) {
throw new Error("Could not load user provided overrides for ClassFiltering from as " + prop + " does not exist or is not readable.");
}
BufferedReader br = null;
try {
br = new BufferedReader(new InputStreamReader(new FileInputStream(prop), Charset.defaultCharset()));
ArrayList<Pattern> patterns = new ArrayList<Pattern>();
for (String line = br.readLine(); line != null; line = br.readLine()) {
try {
patterns.add(Pattern.compile(line));
} catch (PatternSyntaxException pex) {
throw new Error("Error compiling blacklist expressions - '" + line + "' is not a valid regular expression.", pex);
}
}
return patterns;
} catch (IOException ex) {
throw new Error("Could not load user provided overrides for ClassFiltering from as "+prop+" does not exist or is not readable.",ex);
} finally {
if (br != null) {
try {
br.close();
} catch (IOException ioEx) {
LOGGER.log(Level.WARNING, "Failed to cleanly close input stream", ioEx);
}
}
}
}
/**
* A class that uses a given set of regular expression patterns to determine if the class is blacklisted.
*/
private static final class RegExpClassFilter extends ClassFilter {
private final List<Pattern> blacklistPatterns;
public RegExpClassFilter(List<Pattern> blacklistPatterns) {
this.blacklistPatterns = blacklistPatterns;
}
RegExpClassFilter(String[] patterns) {
blacklistPatterns = new ArrayList<Pattern>(patterns.length);
for (String pattern : patterns) {
blacklistPatterns.add(Pattern.compile(pattern));
}
}
@Override
protected boolean isBlacklisted(String name) {
for (Pattern p : blacklistPatterns) {
if (p.matcher(name).matches()) {
return true;
}
}
return false;
}
/**
* Report the patterns that it's using to help users verify the use of custom filtering rule
* and inspect its content at runtime if necessary.
*/
@Override
public String toString() {
return blacklistPatterns.toString();
}
}
}
/*
Publicized attack payload:
ObjectInputStream.readObject()
PriorityQueue.readObject()
Comparator.compare() (Proxy)
ConvertedClosure.invoke()
MethodClosure.call()
Method.invoke()
Runtime.exec()
ObjectInputStream.readObject()
AnnotationInvocationHandler.readObject()
Map(Proxy).entrySet()
AnnotationInvocationHandler.invoke()
LazyMap.get()
ChainedTransformer.transform()
ConstantTransformer.transform()
InvokerTransformer.transform()
Method.invoke()
Class.getMethod()
InvokerTransformer.transform()
Method.invoke()
Runtime.getRuntime()
InvokerTransformer.transform()
Method.invoke()
Runtime.exec()
ObjectInputStream.readObject()
PriorityQueue.readObject()
TransformingComparator.compare()
InvokerTransformer.transform()
Method.invoke()
Runtime.exec()
ObjectInputStream.readObject()
SerializableTypeWrapper.MethodInvokeTypeProvider.readObject()
SerializableTypeWrapper.TypeProvider(Proxy).getType()
AnnotationInvocationHandler.invoke()
HashMap.get()
ReflectionUtils.findMethod()
SerializableTypeWrapper.TypeProvider(Proxy).getType()
AnnotationInvocationHandler.invoke()
HashMap.get()
ReflectionUtils.invokeMethod()
Method.invoke()
Templates(Proxy).newTransformer()
AutowireUtils.ObjectFactoryDelegatingInvocationHandler.invoke()
ObjectFactory(Proxy).getObject()
AnnotationInvocationHandler.invoke()
HashMap.get()
Method.invoke()
TemplatesImpl.newTransformer()
TemplatesImpl.getTransletInstance()
TemplatesImpl.defineTransletClasses()
TemplatesImpl.TransletClassLoader.defineClass()
Pwner*(Javassist-generated).<static init>
Runtime.exec()
*/
|
package kay.kaySkillz.common;
import cpw.mods.fml.common.Mod;
import cpw.mods.fml.common.gameevent.TickEvent;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
import kay.kayXEnchants.common.NBTStuff;
import net.minecraft.entity.monster.EntitySkeleton;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.potion.Potion;
import net.minecraft.potion.PotionEffect;
import net.minecraft.util.ChatComponentText;
import net.minecraft.util.DamageSource;
import java.lang.reflect.Array;
import java.util.EnumSet;
import java.util.EventListener;
public class Events implements EventListener {
@Mod.EventHandler
@SideOnly(Side.SERVER)
public void Tick(EnumSet<TickEvent.Type> type, Object... tickData) {
if (type.contains(TickEvent.Type.PLAYER)) {
EntityPlayer player = (EntityPlayer) tickData[0];
boolean Fly = false;
if (Config.FlySkillEnable) {
if (NBTStuff.SkillAgilityLVL >= 1000) {
Fly = true;
} else {
Fly = false;
}
}
if (Fly == true) {
player.capabilities.allowFlying = true;
if (player.capabilities.isFlying && player.worldObj.isRemote) {
int MaxFlyHeight = NBTStuff.SkillAgilityLVL - 940;
int h = (int) player.getEyeHeight();
player.addExhaustion(1);
player.worldObj.spawnParticle("smoke", player.posX + Math.random() - 0.5d, player.posY - 1.62d, player.posZ + Math.random() - 0.5d, 0.0d, 0.0d, 0.0d);
if (h > MaxFlyHeight){
player.addChatMessage(new ChatComponentText("\u00A74You are not skilled enough to fly this high!"));
player.addPotionEffect(new PotionEffect(Potion.confusion.id, 5, 2, false));
player.addPotionEffect(new PotionEffect(Potion.blindness.id, 5, 2, false));
player.addPotionEffect(new PotionEffect(Potion.digSlowdown.id, 5, 2, false));
player.addPotionEffect(new PotionEffect(Potion.moveSlowdown.id, 5, 2, false));
player.addPotionEffect(new PotionEffect(Potion.weakness.id, 5, 2, false));
player.addPotionEffect(new PotionEffect(Potion.wither.id, 5, 2, false));
}
}
}
}
}
public EnumSet<TickEvent.Type> ticks() {
return EnumSet.of(TickEvent.Type.PLAYER);
}
@Mod.EventHandler
@SideOnly(Side.SERVER)
public void onPlayerTick(TickEvent.PlayerTickEvent event) {
EntityPlayer player = event.player;
int XPGainPF = Config.XPRate * 3;
int XPGainPR = Config.XPRate * 5;
if (event.type.equals(DamageSource.fall) && (event.player != null) && !player.worldObj.isRemote && Config.AgilitySkillEnable)
if (!player.capabilities.isCreativeMode)
if (Config.EnableAgilityReq)
if (player.getCurrentArmor(3) != null) {
if (event.player.isSneaking() && event.player.fallDistance <= NBTStuff.SkillAgilityLVL * Config.BaseStatModifier) {
event.setCanceled(true);
NBTStuff.SkillAgilityXP = NBTStuff.SkillAgilityXP + XPGainPR;
}
}
if (!Config.EnableAgilityReq) {
if (event.player.fallDistance <= NBTStuff.SkillAgilityLVL * Config.BaseStatModifier) {
if (event.player.isSneaking())
event.setCanceled(true);
NBTStuff.SkillAgilityXP = NBTStuff.SkillAgilityXP + XPGainPR;
if (!event.player.isSneaking())
event.setCanceled(false);
NBTStuff.SkillAgilityXP = NBTStuff.SkillAgilityXP + XPGainPF;
}
else{
NBTStuff.SkillAgilityXP = NBTStuff.SkillAgilityXP - Config.XPRate;
if (NBTStuff.SkillAgilityLVL >= 100){
float dmg = event.player.fallDistance - NBTStuff.SkillAgilityLVL;
float Damage = dmg * -1;
event.setCanceled(true);
player.heal(Damage);
}
}
}
if (event.type.equals(DamageSource.magic) || event.type.equals(DamageSource.wither) && (event.player != null) && !player.worldObj.isRemote && Config.ImunityToPoisonSkillEnable){
if (!player.capabilities.isCreativeMode && event.player.fallDistance <= NBTStuff.SkillImmuneLVL * Config.BaseStatModifier) {
if (NBTStuff.SkillImmuneLVL >= 1000)
event.setCanceled(true);
else
event.setCanceled(false);
if (NBTStuff.SkillImmuneLVL >= 25)
player.addPotionEffect(new PotionEffect(Potion.regeneration.id, NBTStuff.SkillImmuneLVL / 250, 2));
}else{
NBTStuff.SkillImmuneXP = NBTStuff.SkillImmuneXP - Config.XPRate;
if (NBTStuff.SkillImmuneLVL >= 100){
float dmg = event.player.fallDistance - NBTStuff.SkillImmuneLVL;
float Damage = dmg * -1;
event.setCanceled(true);
player.heal(Damage);
}
}
}
}
}
|
package logbook.internal;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Supplier;
import javax.json.JsonArray;
import javax.json.JsonNumber;
import javax.json.JsonObject;
import javax.json.JsonString;
import javax.json.JsonValue;
/**
* JsonObject
*
*/
public final class JsonHelper {
/**
* JsonNumberLong
*
* @see JsonNumber#longValue()
* @see BigDecimal#longValue()
* @param val LongJsonValue
* @return Long
*/
public static Long toLong(JsonValue val) {
if (val instanceof JsonNumber) {
return ((JsonNumber) val).longValue();
}
return new BigDecimal(toString(val)).longValue();
}
/**
* JsonValueInteger
*
* @see JsonNumber#intValue()
* @see BigDecimal#intValue()
* @param val IntegerJsonValue
* @return Integer
*/
public static Integer toInteger(JsonValue val) {
if (val instanceof JsonNumber) {
return ((JsonNumber) val).intValue();
}
return new BigDecimal(toString(val)).intValue();
}
/**
* JsonValueDouble
*
* @see JsonNumber#doubleValue()
* @see BigDecimal#doubleValue()
* @param val DoubleJsonValue
* @return Double
*/
public static Double toDouble(JsonValue val) {
if (val instanceof JsonNumber) {
return ((JsonNumber) val).doubleValue();
}
return new BigDecimal(toString(val)).doubleValue();
}
/**
* JsonValueBigDecimal
*
* @see JsonNumber#bigDecimalValue()
* @param val BigDecimalJsonValue
* @return BigDecimal
*/
public static BigDecimal toBigDecimal(JsonValue val) {
if (val instanceof JsonNumber) {
return ((JsonNumber) val).bigDecimalValue();
}
return new BigDecimal(toString(val));
}
/**
* JsonValueString
*
* @see JsonString#getString()
* @see JsonValue#toString()
* @param val StringJsonValue
* @return String
*/
public static String toString(JsonValue val) {
return toObject(val, v -> {
if (v instanceof JsonString) {
return ((JsonString) v).getString();
}
return v.toString();
});
}
/**
* JsonValueBoolean
*
* @param val BooleanJsonValue
* @return JsonNumber BigDecimal.ZERO trueBigDecimal.ZEROfalse<br>
* JsonNumber JsonValue.FALSE truesonValue.FALSEfalse<br>
*/
public static Boolean toBoolean(JsonValue val) {
return toObject(val, v -> {
if (v instanceof JsonNumber) {
// JsonNumber BigDecimal.ZERO truefalse
return BigDecimal.ZERO.compareTo(((JsonNumber) v).bigDecimalValue()) != 0;
}
return v != JsonValue.FALSE;
});
}
/**
* JsonValue
*
* @param <T> JsonValue
* @param <R> function
* @param val RJsonValue
* @param function Function
* @return
*/
public static <T extends JsonValue, R> R toObject(T val, Function<T, R> function) {
if (val == null || val == JsonValue.NULL) {
return null;
}
return function.apply(val);
}
/**
* JsonArrayLongList<br>
* JsonArrayJsonNumber
*
* @param val JsonArray
* @return LongList
*/
public static List<Long> toLongList(JsonArray val) {
return toList(val, JsonHelper::toLong);
}
/**
* JsonValueLongList<br>
* valJsonArrayJsonNumber<br>
* valJsonArray{@code Collections#emptyList()}<br>
*
* @param val JsonValue
* @return LongList
*/
public static List<Long> checkedToLongList(JsonValue val) {
if (val instanceof JsonArray) {
return toList((JsonArray) val, JsonHelper::toLong);
}
return Collections.emptyList();
}
/**
* JsonArrayIntegerList<br>
* JsonArrayJsonNumber
*
* @param val JsonArray
* @return IntegerList
*/
public static List<Integer> toIntegerList(JsonArray val) {
return toList(val, JsonHelper::toInteger);
}
/**
* JsonValueIntegerList<br>
* valJsonArrayJsonNumber<br>
* valJsonArray{@code Collections#emptyList()}<br>
*
* @param val JsonArray
* @return IntegerList
*/
public static List<Integer> checkedToIntegerList(JsonValue val) {
if (val instanceof JsonArray) {
return toList((JsonArray) val, JsonHelper::toInteger);
}
return Collections.emptyList();
}
/**
* JsonArrayDoubleList<br>
* JsonArrayJsonNumber
*
* @param val JsonArray
* @return DoubleList
*/
public static List<Double> toDoubleList(JsonArray val) {
return toList(val, JsonHelper::toDouble);
}
/**
* JsonValueDoubleList<br>
* valJsonArrayJsonNumber<br>
* valJsonArray{@code Collections#emptyList()}<br>
*
* @param val JsonArray
* @return DoubleList
*/
public static List<Double> checkedToDoubleList(JsonValue val) {
if (val instanceof JsonArray) {
return toList((JsonArray) val, JsonHelper::toDouble);
}
return Collections.emptyList();
}
/**
* JsonArrayBigDecimalList<br>
* JsonArrayJsonNumber
*
* @param val JsonArray
* @return BigDecimalList
*/
public static List<BigDecimal> toBigDecimalList(JsonArray val) {
return toList(val, JsonHelper::toBigDecimal);
}
/**
* JsonValueBigDecimalList<br>
* valJsonArrayJsonNumber<br>
* valJsonArray{@code Collections#emptyList()}<br>
*
* @param val JsonArray
* @return BigDecimalList
*/
public static List<BigDecimal> checkedToBigDecimalList(JsonValue val) {
if (val instanceof JsonArray) {
return toList((JsonArray) val, JsonHelper::toBigDecimal);
}
return Collections.emptyList();
}
/**
* JsonArrayStringList<br>
*
* @param val JsonArray
* @return StringList
*/
public static List<String> toStringList(JsonArray val) {
return toList(val, JsonHelper::toString);
}
/**
* JsonValueStringList<br>
* valJsonArray{@code Collections#emptyList()}<br>
*
* @param val JsonArray
* @return StringList
*/
public static List<String> checkedToStringList(JsonValue val) {
if (val instanceof JsonArray) {
return toList((JsonArray) val, JsonHelper::toString);
}
return Collections.emptyList();
}
/**
* JsonArrayLongSet<br>
* JsonArrayJsonNumber
*
* @param val JsonArray
* @return LongSet
*/
public static Set<Long> toLongSet(JsonArray val) {
return toSet(val, JsonHelper::toLong);
}
/**
* JsonValueLongSet<br>
* valJsonArrayJsonNumber<br>
* valJsonArray{@code Collections#emptySet()}<br>
*
* @param val JsonValue
* @return LongSet
*/
public static Set<Long> checkedToLongSet(JsonValue val) {
if (val instanceof JsonArray) {
return toSet((JsonArray) val, JsonHelper::toLong);
}
return Collections.emptySet();
}
/**
* JsonArrayIntegerSet<br>
* JsonArrayJsonNumber
*
* @param val JsonArray
* @return IntegerSet
*/
public static Set<Integer> toIntegerSet(JsonArray val) {
return toSet(val, JsonHelper::toInteger);
}
/**
* JsonValueIntegerSet<br>
* valJsonArrayJsonNumber<br>
* valJsonArray{@code Collections#emptySet()}<br>
*
* @param val JsonArray
* @return IntegerSet
*/
public static Set<Integer> checkedToIntegerSet(JsonValue val) {
if (val instanceof JsonArray) {
return toSet((JsonArray) val, JsonHelper::toInteger);
}
return Collections.emptySet();
}
/**
* JsonArrayDoubleSet<br>
* JsonArrayJsonNumber
*
* @param val JsonArray
* @return DoubleSet
*/
public static Set<Double> toDoubleSet(JsonArray val) {
return toSet(val, JsonHelper::toDouble);
}
/**
* JsonValueDoubleSet<br>
* valJsonArrayJsonNumber<br>
* valJsonArray{@code Collections#emptySet()}<br>
*
* @param val JsonArray
* @return DoubleSet
*/
public static Set<Double> checkedToDoubleSet(JsonValue val) {
if (val instanceof JsonArray) {
return toSet((JsonArray) val, JsonHelper::toDouble);
}
return Collections.emptySet();
}
/**
* JsonArrayBigDecimalSet<br>
* JsonArrayJsonNumber
*
* @param val JsonArray
* @return BigDecimalSet
*/
public static Set<BigDecimal> toBigDecimalSet(JsonArray val) {
return toSet(val, JsonHelper::toBigDecimal);
}
/**
* JsonValueBigDecimalSet<br>
* valJsonArrayJsonNumber<br>
* valJsonArray{@code Collections#emptySet()}<br>
*
* @param val JsonArray
* @return BigDecimalSet
*/
public static Set<BigDecimal> checkedToBigDecimalSet(JsonValue val) {
if (val instanceof JsonArray) {
return toSet((JsonArray) val, JsonHelper::toBigDecimal);
}
return Collections.emptySet();
}
/**
* JsonArrayStringSet<br>
*
* @param val JsonArray
* @return StringSet
*/
public static Set<String> toStringSet(JsonArray val) {
return toSet(val, JsonHelper::toString);
}
/**
* JsonValueStringSet<br>
* valJsonArray{@code Collections#emptySet()}<br>
*
* @param val JsonArray
* @return StringSet
*/
public static Set<String> checkedToStringSet(JsonValue val) {
if (val instanceof JsonArray) {
return toSet((JsonArray) val, JsonHelper::toString);
}
return Collections.emptySet();
}
/**
* JsonArrayJsonObjectCollection<br>
* JsonObjectCollection
*
* @param <T> JsonArray
* @param <R> function
* @param <C> Collection
* @param value JsonArrayJsonObject
* @param function JsonValueFunction
* @param supplier CollectionSupplier
* @return Collection
*/
@SuppressWarnings("unchecked")
public static <T extends JsonValue, C extends Collection<R>, R> C toCollection(JsonValue value,
Function<T, R> function, Supplier<C> supplier) {
C collection = supplier.get();
if (value instanceof JsonArray) {
for (JsonValue val : (JsonArray) value) {
if (val == null || val == JsonValue.NULL) {
collection.add(null);
} else {
collection.add(function.apply((T) val));
}
}
} else {
collection.add(function.apply((T) value));
}
return collection;
}
/**
* JsonArrayList
*
* @param <T> JsonArray
* @param <R> function
* @param value JsonArrayJsonObject
* @param function JsonValueFunction
* @return List
*/
public static <T extends JsonValue, R> List<R> toList(JsonValue value, Function<T, R> function) {
return toCollection(value, function, ArrayList::new);
}
/**
* JsonArrayList
*
* @param <T> JsonArray
* @param <R> function
* @param function JsonValueFunction
* @return List
*/
public static <T extends JsonValue, R> Function<JsonValue, List<R>> toList(Function<T, R> function) {
return val -> JsonHelper.toList(val, function);
}
/**
* JsonArraySet
*
* @param <T> JsonArray
* @param <R> function
* @param value JsonArrayJsonObject
* @param function JsonValueFunction
* @return Set
*/
public static <T extends JsonValue, R> Set<R> toSet(JsonValue value, Function<T, R> function) {
return toCollection(value, function, LinkedHashSet::new);
}
/**
* JsonArraySet
*
* @param <T> JsonArray
* @param <R> function
* @param function JsonValueFunction
* @return Set
*/
public static <T extends JsonValue, R> Function<JsonValue, Set<R>> toSet(Function<T, R> function) {
return val -> JsonHelper.toSet(val, function);
}
/**
* JsonArrayMap
*
* @param <T> JsonArray
* @param <K> Map
* @param <R> Map
* @param array JsonArray
* @param keyMapper valueMapperFunction
* @param valueMapper arrayJsonValueFunction
* @return Map
*/
@SuppressWarnings("unchecked")
public static <T extends JsonValue, K, R> Map<K, R> toMap(JsonArray array, Function<R, K> keyMapper,
Function<T, R> valueMapper) {
Map<K, R> map = new LinkedHashMap<>();
for (JsonValue val : array) {
R r = valueMapper.apply((T) val);
map.put(keyMapper.apply(r), r);
}
return map;
}
/**
* JsonObjectMap
*
* @param <T> JsonObject
* @param <K> Map
* @param <R> Map
* @param obj JsonObject
* @param keyMapper JsonObjectFunction
* @param valueMapper arrayJsonValueFunction
* @return Map
*/
@SuppressWarnings("unchecked")
public static <T extends JsonValue, K, R> Map<K, R> toMap(JsonObject obj, Function<String, K> keyMapper,
Function<T, R> valueMapper) {
Map<K, R> map = new LinkedHashMap<>();
obj.forEach((k, v) -> {
R r = valueMapper.apply((T) v);
map.put(keyMapper.apply(k), r);
});
return map;
}
/**
* JsonObject<br>
* <br>
* beanJSON<br>
* JSON<br>
* <pre><code>{"api_id" : 558, "api_name" : "", "api_type" : [ 3, 5, 8, 8 ]}</code></pre>
* Java<br>
* <pre><code>JsonHelper.bind(json)
* .set("api_id", bean::setId, JsonHelper::toInteger)
* .set("api_name", bean::setName, JsonHelper::toString)
* .set("api_type", bean::setType, JsonHelper::toIntegerList);</code></pre>
*
* @param json JsonObject
* @return {@link Bind}
*/
public static Bind bind(JsonObject json) {
return new Bind(json);
}
/**
* JsonObject<br>
* <br>
* beanJSON<br>
* JSON<br>
* <pre><code>{"api_id" : 558, "api_name" : "", "api_type" : [ 3, 5, 8, 8 ]}</code></pre>
* Java<br>
* <pre><code>JsonHelper.bind(json)
* .set("api_id", bean::setId, JsonHelper::toInteger)
* .set("api_name", bean::setName, JsonHelper::toString)
* .set("api_type", bean::setType, JsonHelper::toIntegerList);</code></pre>
*
* @param json JsonObject
* @param listener BindListener
* @return {@link Bind}
*/
public static Bind bind(JsonObject json, BindListener listener) {
return new Bind(json, listener);
}
/**
* JsonObject<br>
*
*/
public static class Bind {
private JsonObject json;
private BindListener listener;
/**
*
*
* @param json JsonObject
*/
private Bind(JsonObject json) {
this.json = json;
}
/**
*
*
* @param json JsonObject
* @param listener BindListener
*/
private Bind(JsonObject json, BindListener listener) {
this.json = json;
this.listener = listener;
}
/**
* keyJsonValueconverterconsumer<br>
*
* @param <T> JsonObject#get(Object)
* @param <R> converter
* @param key JsonObject
* @param consumer converterConsumer
* @param converter JsonValueFunction
* @return {@link Bind}
*/
@SuppressWarnings("unchecked")
public <T extends JsonValue, R> Bind set(String key, Consumer<R> consumer, Function<T, R> converter) {
JsonValue val = this.json.get(key);
if (val != null && JsonValue.NULL != val) {
R obj = converter.apply((T) val);
consumer.accept(obj);
if (this.listener != null) {
this.listener.apply(key, val, obj);
}
}
return this;
}
/**
* keyJsonValueStringconsumer<br>
*
* @param key JsonObject
* @param consumer converterConsumer
* @return {@link Bind}
*/
public Bind setString(String key, Consumer<String> consumer) {
return this.set(key, consumer, JsonHelper::toString);
}
/**
* keyJsonValueIntegerconsumer<br>
*
* @param key JsonObject
* @param consumer converterConsumer
* @return {@link Bind}
*/
public Bind setInteger(String key, Consumer<Integer> consumer) {
return this.set(key, consumer, JsonHelper::toInteger);
}
/**
* keyJsonValueLongconsumer<br>
*
* @param key JsonObject
* @param consumer converterConsumer
* @return {@link Bind}
*/
public Bind setLong(String key, Consumer<Long> consumer) {
return this.set(key, consumer, JsonHelper::toLong);
}
/**
* keyJsonValueDoubleconsumer<br>
*
* @param key JsonObject
* @param consumer converterConsumer
* @return {@link Bind}
*/
public Bind setDouble(String key, Consumer<Double> consumer) {
return this.set(key, consumer, JsonHelper::toDouble);
}
/**
* keyJsonValueBigDecimalconsumer<br>
*
* @param key JsonObject
* @param consumer converterConsumer
* @return {@link Bind}
*/
public Bind setBigDecimal(String key, Consumer<BigDecimal> consumer) {
return this.set(key, consumer, JsonHelper::toBigDecimal);
}
/**
* keyJsonValueBooleanconsumer<br>
*
* @param key JsonObject
* @param consumer converterConsumer
* @return {@link Bind}
*/
public Bind setBoolean(String key, Consumer<Boolean> consumer) {
return this.set(key, consumer, JsonHelper::toBoolean);
}
}
/**
* {@link Bind}
*/
public static interface BindListener {
/**
*
*
* @param key JsonObject
* @param val JsonObject
* @param obj converter
*/
void apply(String key, JsonValue val, Object obj);
}
}
|
package mezz.jei.gui;
import com.google.common.collect.ImmutableList;
import javax.annotation.Nonnull;
import java.util.ArrayList;
import java.util.List;
import mezz.jei.api.JEIManager;
import mezz.jei.api.recipe.IRecipeCategory;
import mezz.jei.api.recipe.IRecipeHandler;
import mezz.jei.api.recipe.IRecipeWrapper;
import mezz.jei.util.Log;
import mezz.jei.util.MathUtil;
public class RecipeGuiLogic implements IRecipeGuiLogic {
/* Whether this GUI is dispzzlaying input or output recipes */
private Mode mode;
/* The focus of this GUI */
@Nonnull
private Focus focus = new Focus();
/* List of Recipe Categories that involve the focus */
@Nonnull
private ImmutableList<IRecipeCategory> recipeCategories = ImmutableList.of();
/* List of recipes for the currently selected recipeClass */
@Nonnull
private ImmutableList<Object> recipes = ImmutableList.of();
private int recipesPerPage = 0;
private int recipeCategoryIndex = 0;
private int pageIndex = 0;
@Override
public boolean setFocus(@Nonnull Focus focus, @Nonnull Mode mode) {
if (this.focus.equals(focus) && this.mode == mode) {
return true;
}
ImmutableList<IRecipeCategory> types = null;
switch (mode) {
case INPUT:
types = focus.getCategoriesWithInput();
break;
case OUTPUT:
types = focus.getCategoriesWithOutput();
break;
}
if (types.isEmpty()) {
return false;
}
this.recipeCategories = types;
this.focus = focus;
this.mode = mode;
this.recipeCategoryIndex = 0;
this.pageIndex = 0;
updateRecipes();
return true;
}
@Override
public void setRecipesPerPage(int recipesPerPage) {
if (this.recipesPerPage != recipesPerPage) {
int recipeIndex = pageIndex * this.recipesPerPage;
this.pageIndex = recipeIndex / recipesPerPage;
this.recipesPerPage = recipesPerPage;
updateRecipes();
}
}
private void updateRecipes() {
IRecipeCategory recipeCategory = getRecipeCategory();
switch (mode) {
case INPUT:
recipes = focus.getRecipesWithInput(recipeCategory);
break;
case OUTPUT:
recipes = focus.getRecipesWithOutput(recipeCategory);
break;
}
}
@Override
public IRecipeCategory getRecipeCategory() {
if (recipeCategories.size() == 0) {
return null;
}
return recipeCategories.get(recipeCategoryIndex);
}
@Override
@Nonnull
public List<RecipeWidget> getRecipeWidgets() {
List<RecipeWidget> recipeWidgets = new ArrayList<>();
IRecipeCategory recipeCategory = getRecipeCategory();
if (recipeCategory == null) {
return recipeWidgets;
}
for (int recipeIndex = pageIndex * recipesPerPage; recipeIndex < recipes.size() && recipeWidgets.size() < recipesPerPage; recipeIndex++) {
Object recipe = recipes.get(recipeIndex);
IRecipeHandler recipeHandler = JEIManager.recipeRegistry.getRecipeHandler(recipe.getClass());
if (recipeHandler == null) {
Log.error("Couldn't find recipe handler for recipe: {}", recipe);
continue;
}
RecipeWidget recipeWidget = new RecipeWidget(recipeCategory);
@SuppressWarnings("unchecked")
IRecipeWrapper recipeWrapper = recipeHandler.getRecipeWrapper(recipe);
recipeWidget.setRecipe(recipeWrapper, focus);
recipeWidgets.add(recipeWidget);
}
return recipeWidgets;
}
@Override
public void nextRecipeCategory() {
int recipesTypesCount = recipeCategories.size();
recipeCategoryIndex = (recipeCategoryIndex + 1) % recipesTypesCount;
pageIndex = 0;
updateRecipes();
}
@Override
public boolean hasMultiplePages() {
return recipes.size() > recipesPerPage;
}
@Override
public void previousRecipeCategory() {
int recipesTypesCount = recipeCategories.size();
recipeCategoryIndex = (recipesTypesCount + recipeCategoryIndex - 1) % recipesTypesCount;
pageIndex = 0;
updateRecipes();
}
@Override
public void nextPage() {
int pageCount = pageCount(recipesPerPage);
pageIndex = (pageIndex + 1) % pageCount;
updateRecipes();
}
@Override
public void previousPage() {
int pageCount = pageCount(recipesPerPage);
pageIndex = (pageCount + pageIndex - 1) % pageCount;
updateRecipes();
}
private int pageCount(int recipesPerPage) {
if (recipes.size() <= 1) {
return 1;
}
return MathUtil.divideCeil(recipes.size(), recipesPerPage);
}
@Override
@Nonnull
public String getPageString() {
return (pageIndex + 1) + "/" + pageCount(recipesPerPage);
}
@Override
public boolean hasMultipleCategories() {
return recipeCategories.size() > 1;
}
}
|
package net.imagej.legacy;
import ij.Executer;
import ij.IJ;
import ij.ImageJ;
import ij.ImagePlus;
import ij.Macro;
import ij.Menus;
import ij.WindowManager;
import ij.gui.ImageWindow;
import ij.gui.Toolbar;
import ij.io.Opener;
import ij.macro.Interpreter;
import ij.plugin.Commands;
import ij.plugin.PlugIn;
import ij.plugin.filter.PlugInFilter;
import ij.plugin.filter.PlugInFilterRunner;
import ij.plugin.frame.PlugInDialog;
import ij.plugin.frame.PlugInFrame;
import ij.text.TextWindow;
import java.awt.Component;
import java.awt.Image;
import java.awt.Menu;
import java.awt.MenuBar;
import java.awt.MenuItem;
import java.awt.Window;
import java.awt.image.ImageProducer;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.Method;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.List;
import java.util.Map;
import javax.swing.SwingUtilities;
import net.imagej.display.ImageDisplay;
import net.imagej.patcher.LegacyHooks;
import org.scijava.AbstractContextual;
import org.scijava.Context;
import org.scijava.MenuEntry;
import org.scijava.MenuPath;
import org.scijava.command.CommandInfo;
import org.scijava.event.EventHandler;
import org.scijava.log.LogService;
import org.scijava.platform.event.AppAboutEvent;
import org.scijava.platform.event.AppOpenFilesEvent;
import org.scijava.platform.event.AppPreferencesEvent;
import org.scijava.platform.event.AppQuitEvent;
import org.scijava.plugin.Parameter;
import org.scijava.script.ScriptService;
import org.scijava.util.ClassUtils;
/**
* A helper class to interact with ImageJ 1.x.
* <p>
* The DefaultLegacyService needs to patch ImageJ 1.x's classes before they are
* loaded. Unfortunately, this is tricky: if the DefaultLegacyService already
* uses those classes, it is a matter of luck whether we can get the patches in
* before those classes are loaded.
* </p>
* <p>
* Therefore, we put as much interaction with ImageJ 1.x as possible into this
* class and keep a reference to it in the DefaultLegacyService.
* </p>
*
* @author Johannes Schindelin
*/
public class IJ1Helper extends AbstractContextual {
/** A reference to the legacy service, just in case we need it */
private final DefaultLegacyService legacyService;
@Parameter
private LogService log;
public IJ1Helper(final DefaultLegacyService legacyService) {
setContext(legacyService.getContext());
this.legacyService = legacyService;
}
public void initialize() {
// initialize legacy ImageJ application
final ImageJ ij1 = IJ.getInstance();
if (Menus.getCommands() == null) {
IJ.runPlugIn("ij.IJ.init", "");
}
if (ij1 != null) {
// make sure that the Event Dispatch Thread's class loader is set
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
Thread.currentThread().setContextClassLoader(IJ.getClassLoader());
}
});
final LegacyImageMap imageMap = legacyService.getImageMap();
for (int i = 1; i <= WindowManager.getImageCount(); i++) {
imageMap.registerLegacyImage(WindowManager.getImage(i));
}
// set icon and title of main window (which are instantiated before the
// initializer is called)
try {
final LegacyHooks hooks =
(LegacyHooks) IJ.class.getField("_hooks").get(null);
ij1.setTitle(hooks.getAppName());
final URL iconURL = hooks.getIconURL();
if (iconURL != null) try {
final Object producer = iconURL.getContent();
final Image image = ij1.createImage((ImageProducer) producer);
ij1.setIconImage(image);
if (IJ.isMacOSX()) try {
// NB: We also need to set the dock icon
final Class<?> clazz = Class.forName("com.apple.eawt.Application");
final Object app = clazz.getMethod("getApplication").invoke(null);
clazz.getMethod("setDockIconImage", Image.class).invoke(app, image);
}
catch (final Throwable t) {
t.printStackTrace();
}
}
catch (final IOException e) {
IJ.handleException(e);
}
}
catch (final Throwable t) {
t.printStackTrace();
}
}
}
public void dispose() {
final ImageJ ij = IJ.getInstance();
if (ij != null) {
Runnable run = new Runnable() {
@Override
public void run() {
// close out all image windows, without dialog prompts
while (true) {
final ImagePlus imp = WindowManager.getCurrentImage();
if (imp == null) break;
imp.changes = false;
imp.close();
}
}
};
if (SwingUtilities.isEventDispatchThread()) {
run.run();
} else try {
SwingUtilities.invokeAndWait(run);
} catch (Exception e) {
// report & ignore
e.printStackTrace();
}
// We need to ensure all the non-image windows are closed in ImageJ 1.x.
// This is a non-trivial problem, as WindowManager#getNonImageWindows()
// will ONLY return Frames. However there are non-Frame, non-Image Windows
// that are critical to close: for example, the ContrastAdjuster spawns
// a polling thread to do its work, which will continue to run until the
// ContrastAdjuster is explicitly closed.
// As of v1.49b, getNonImageTitles is not restricted to Frames, so we must
// use titles to iterate through the available windows.
for (String title : WindowManager.getNonImageTitles()) {
// Titles are not unique in IJ1, but since we are iterating through all
// the available Windows, duplicates will each get handled eventually.
final Window win = WindowManager.getWindow(title);
// Copied from ij.plugin.Commands.close. These are subclasses of
// java.awt.Window that added close methods. These methods absolutely
// need to be called - the only reason this is working in ImageJ 1.x
// right now is that ImageJ.exitWhenQuitting is always true, as there
// is nothing setting it to false. So System.exit(0) is called and it
// doesn't matter that there may be unclosed windows or utility threads
// running.
// In ImageJ2 however we need to ensure these windows are properly shut
// down.
// Note that we can NOT set these windows as active and run the Commands
// plugin with argument "close", because the default behavior is to
// try closing the window as an Image. As we know these are not Images,
// that is never the right thing to do.
if (win instanceof PlugInFrame)
((PlugInFrame)win).close();
else if (win instanceof PlugInDialog)
((PlugInDialog)win).close();
else if (win instanceof TextWindow)
((TextWindow)win).close();
// Ensure the WindowManager has removed the current window and it has
// been disposed. This may cause double disposal, but as far as we know
// that is OK.
WindowManager.removeWindow(win);
win.dispose();
}
// quit legacy ImageJ on the same thread
ij.run();
}
}
/** Add name aliases for ImageJ1 classes to the ScriptService. */
public void addAliases(final ScriptService scriptService) {
scriptService.addAlias(ImagePlus.class);
}
public boolean isVisible() {
final ImageJ ij = IJ.getInstance();
if (ij == null) return false;
return ij.isVisible();
}
private boolean batchMode;
void setBatchMode(boolean batch) {
Interpreter.batchMode = batch;
batchMode = batch;
}
void invalidateInstance() {
try {
final Method cleanup = IJ.class.getDeclaredMethod("cleanup");
cleanup.setAccessible(true);
cleanup.invoke(null);
} catch (Throwable t) {
t.printStackTrace();
legacyService.log().error(t);
}
}
public void setVisible(boolean toggle) {
if (batchMode) return;
final ImageJ ij = IJ.getInstance();
if (ij != null) {
if (toggle) ij.pack();
ij.setVisible(toggle);
}
// hide/show the legacy ImagePlus instances
final LegacyImageMap imageMap = legacyService.getImageMap();
for (final ImagePlus imp : imageMap.getImagePlusInstances()) {
final ImageWindow window = imp.getWindow();
if (window != null) window.setVisible(toggle);
}
}
public void syncActiveImage(final ImageDisplay activeDisplay) {
final LegacyImageMap imageMap = legacyService.getImageMap();
final ImagePlus activeImagePlus = imageMap.lookupImagePlus(activeDisplay);
// NB - old way - caused probs with 3d Project
// WindowManager.setTempCurrentImage(activeImagePlus);
// NB - new way - test thoroughly
if (activeImagePlus == null) WindowManager.setCurrentWindow(null);
else WindowManager.setCurrentWindow(activeImagePlus.getWindow());
}
public void setKeyDown(int keyCode) {
IJ.setKeyDown(keyCode);
}
public void setKeyUp(int keyCode) {
IJ.setKeyUp(keyCode);
}
public boolean hasInstance() {
return IJ.getInstance() != null;
}
public String getVersion() {
return ImageJ.VERSION;
}
public boolean isMacintosh() {
return IJ.isMacintosh();
}
public void setStatus(String message) {
IJ.showStatus(message);
}
public void setProgress(int val, int max) {
IJ.showProgress(val, max);
}
public Component getToolBar() {
return Toolbar.getInstance();
}
public ImageJ getIJ() {
if (hasInstance()) {
return IJ.getInstance();
}
return null;
}
public void showMessage(String title, String message) {
IJ.showMessage(title, message);
}
public boolean showMessageWithCancel(String title, String message) {
return IJ.showMessageWithCancel(title, message);
}
public String commandsName() {
return Commands.class.getName();
}
public void updateRecentMenu(final String path) {
Menu menu = Menus.getOpenRecentMenu();
if (menu == null) return;
int n = menu.getItemCount();
int index = -1;
for (int i=0; i<n; i++) {
if (menu.getItem(i).getLabel().equals(path)) {
index = i;
break;
}
}
// Move to most recent
if (index > 0) {
final MenuItem item = menu.getItem(index);
menu.remove(index);
menu.insert(item, 0);
}
// not found, so replace oldest
else if (index < 0) {
int count = menu.getItemCount();
if (count >= Menus.MAX_OPEN_RECENT_ITEMS) {
menu.remove(count - 1);
}
final MenuItem item = new MenuItem(path);
final ImageJ instance = IJ.getInstance();
if (instance != null) item.addActionListener(instance);
menu.insert(item, 0);
}
// if index was 0, already at the head so do nothing
}
/**
* Gets a macro parameter of type <i>boolean</i>.
*
* @param label
* the name of the macro parameter
* @param defaultValue
* the default value
* @return the boolean value
*/
public static boolean getMacroParameter(String label, boolean defaultValue) {
return getMacroParameter(label) != null || defaultValue;
}
/**
* Gets a macro parameter of type <i>double</i>.
*
* @param label
* the name of the macro parameter
* @param defaultValue
* the default value
* @return the double value
*/
public static double getMacroParameter(String label, double defaultValue) {
String value = Macro.getValue(Macro.getOptions(), label, null);
return value != null ? Double.parseDouble(value) : defaultValue;
}
/**
* Gets a macro parameter of type {@link String}.
*
* @param label
* the name of the macro parameter
* @param defaultValue
* the default value
* @return the value
*/
public static String getMacroParameter(String label, String defaultValue) {
return Macro.getValue(Macro.getOptions(), label, defaultValue);
}
/**
* Gets a macro parameter of type {@link String}.
*
* @param label
* the name of the macro parameter
* @return the value, <code>null</code> if the parameter was not specified
*/
public static String getMacroParameter(String label) {
return Macro.getValue(Macro.getOptions(), label, null);
}
/** Gets the SciJava application context linked to the ImageJ 1.x instance. */
public static Context getLegacyContext() {
// NB: This call instantiates a Context if there is none.
// IJ.runPlugIn() will be intercepted by the legacy hooks if they are
// installed and return the current Context.
// If no legacy hooks are installed, ImageJ 1.x will instantiate the Context
// using the PluginClassLoader and the LegacyService will install the legacy
// hooks.
final Object o = IJ.runPlugIn("org.scijava.Context", "");
if (o == null) return null;
if (!(o instanceof Context)) {
throw new IllegalStateException("Unexpected type of context: " +
o.getClass().getName());
}
return (Context) o;
}
/**
* Replacement for ImageJ 1.x' MacAdapter.
* <p>
* ImageJ 1.x has a MacAdapter plugin that intercepts MacOSX-specific events
* and handles them. The way it does it is deprecated now, however, and
* unfortunately incompatible with the way ImageJ 2's platform service does
* it.
* </p>
* <p>
* This class implements the same functionality as the MacAdapter, but in a
* way that is compatible with ImageJ 2's platform service.
* </p>
* @author Johannes Schindelin
*/
private static class LegacyEventDelegator extends AbstractContextual {
@Parameter(required = false)
private LegacyService legacyService;
// -- MacAdapter re-implementations --
@EventHandler
private void onEvent(final AppAboutEvent event)
{
if (isLegacyMode()) {
IJ.run("About ImageJ...");
}
}
@EventHandler
private void onEvent(final AppOpenFilesEvent event) {
if (isLegacyMode()) {
final List<File> files = new ArrayList<File>(event.getFiles());
for (final File file : files) {
new Opener().openAndAddToRecent(file.getAbsolutePath());
}
}
}
@EventHandler
private void onEvent(final AppQuitEvent event) {
if (isLegacyMode()) {
new Executer("Quit", null); // works with the CommandListener
}
}
@EventHandler
private void onEvent(final AppPreferencesEvent event)
{
if (isLegacyMode()) {
IJ.error("The ImageJ preferences are in the Edit>Options menu.");
}
}
private boolean isLegacyMode() {
// We call setContext() indirectly from DefaultLegacyService#initialize,
// therefore legacyService might still be null at this point even if the
// context knows a legacy service now.
if (legacyService == null) {
final Context context = getContext();
if (context != null) legacyService = context.getService(LegacyService.class);
}
return legacyService != null && legacyService.isLegacyMode();
}
}
private static LegacyEventDelegator eventDelegator;
public static void subscribeEvents(final Context context) {
if (context == null) {
eventDelegator = null;
} else {
eventDelegator = new LegacyEventDelegator();
eventDelegator.setContext(context);
IJ.showStatus("");
}
}
static void run(Class<?> c) {
IJ.resetEscape();
if (PlugIn.class.isAssignableFrom(c)) {
try {
final PlugIn plugin = (PlugIn) c.newInstance();
plugin.run("");
} catch (Exception e) {
throw e instanceof RuntimeException ? (RuntimeException) e
: new RuntimeException(e);
}
return;
}
if (PlugInFilter.class.isAssignableFrom(c)) {
try {
final PlugInFilter plugin = (PlugInFilter) c.newInstance();
ImagePlus image = WindowManager.getCurrentImage();
if (image != null && image.isLocked()) {
if (!IJ.showMessageWithCancel("Unlock image?", "The image '" + image.getTitle()
+ "'appears to be locked... Unlock?"))
return;
image.unlock();
}
new PlugInFilterRunner(plugin, c.getName(), "");
} catch (Exception e) {
throw e instanceof RuntimeException ? (RuntimeException) e
: new RuntimeException(e);
}
return;
}
throw new RuntimeException("TODO: construct class loader");
}
/**
* Adds all of the provided commands to the ImageJ1 menu structure.
*/
public void addMenuItems(Collection<CommandInfo> commands) {
@SuppressWarnings("unchecked")
final Hashtable<String, String> ij1Commands = Menus.getCommands();
final ImageJ ij1 = getIJ();
final IJ1MenuWrapper wrapper = ij1 == null ? null : new IJ1MenuWrapper(ij1);
for (final CommandInfo info : commands) {
final MenuEntry leaf = info.getMenuPath().getLeaf();
if (leaf == null) continue;
final MenuPath path = info.getMenuPath();
final String name = leaf.getName();
if (ij1Commands.containsKey(name)) {
legacyService.log().info("Overriding " + name
+ "; class: " + info.getDelegateClassName()
+ "; jar: " + ClassUtils.getLocation(info.getDelegateClassName()));
if (wrapper != null) try {
wrapper.create(path, true);
}
catch (final Throwable t) {
legacyService.log().error(t);
}
}
else if (wrapper != null) try {
wrapper.create(path, false);
}
catch (final Throwable t) {
legacyService.log().error(t);
}
ij1Commands.put(name, info.getDelegateClassName());
}
}
/**
* Helper class for wrapping ImageJ2 menu paths to ImageJ1 {@link Menu}
* structures, and inserting them into the proper positions of the
* {@link MenuBar}.
*/
private static class IJ1MenuWrapper {
final ImageJ ij1;
final MenuBar menuBar = Menus.getMenuBar();
final Map<String, Menu> structure = new HashMap<String, Menu>();
private IJ1MenuWrapper(final ImageJ ij1) {
this.ij1 = ij1;
}
/**
* Creates a {@link MenuItem} matching the structure of the provided path.
* Expected path structure is:
* <p>
* <ul>Level1 > Level2 > ... > Leaf entry</ul>
* </p>
* <p>
* For example, a valid path would be:
* </p>
* <p>
* <ul>Edit > Options > ImageJ2 plugins > Discombobulator</ul>
* </p>
*/
private MenuItem create(final MenuPath path, final boolean reuseExisting) {
// Find the menu structure where we can insert our command.
// NB: size - 1 is the leaf position, so we want to go to size - 2 to
// find the parent menu location
final Menu menu = getParentMenu(path, path.size() - 2);
final String label = path.getLeaf().getName();
// If we are overriding an item, find the item being overridden
if (reuseExisting) {
for (int i = 0; i < menu.getItemCount(); i++) {
final MenuItem item = menu.getItem(i);
if (label.equals(item.getLabel())) {
return item;
}
}
}
// Otherwise, we are creating a new item
final MenuItem item = new MenuItem(label);
menu.insert(item, getIndex(menu, label));
item.addActionListener(ij1);
return item;
}
/**
* Helper method to look up special cases for menu weighting
*/
private int getIndex(Menu menu, String label) {
// Place export sub-menu after import sub-menu
if (menu.getLabel().equals("File") && label.equals("Export")) {
for (int i=0; i<menu.getItemCount(); i++) {
final MenuItem menuItem = menu.getItem(i);
if (menuItem.getLabel().equals("Import")) return i + 1;
}
}
//TODO pass and use actual command weight from IJ2.. maybe?
// No special case: append to end of menu
return menu.getItemCount();
}
/**
* Recursive helper method to builds the final {@link Menu} structure.
*/
private Menu getParentMenu(final MenuPath menuPath, int depth) {
final MenuEntry currentItem = menuPath.get(depth);
final String currentLabel = currentItem.getName();
// Check to see if we already know the menu associated with the desired
// label/path
final Menu cached = structure.get(currentLabel);
if (cached != null) return cached;
// We are at the root of the menu, so see if we have a matching menu
if (depth == 0) {
// Special case check the help menu
if ("Help".equals(currentLabel)) {
final Menu menu = menuBar.getHelpMenu();
structure.put(currentLabel, menu);
return menu;
}
// Check the other menus of the menu bar to see if our desired label
// already exists
for (int i = 0; i < menuBar.getMenuCount(); i++) {
final Menu menu = menuBar.getMenu(i);
if (currentLabel.equals(menu.getLabel())) {
structure.put(currentLabel, menu);
return menu;
}
}
// Didn't find a match so we have to create a new menu entry
final Menu menu = new Menu(currentLabel);
menuBar.add(menu);
structure.put(currentLabel, menu);
return menu;
}
final Menu parent = getParentMenu(menuPath, depth - 1);
// Once the parent of this entry is obtained, we need to check if it
// already contains the current entry.
for (int i = 0; i < parent.getItemCount(); i++) {
final MenuItem item = parent.getItem(i);
if (currentLabel.equals(item.getLabel())) {
if (item instanceof Menu) {
// Found a menu entry that matches our desired label, so return
final Menu menu = (Menu) item;
structure.put(currentLabel, menu);
return menu;
}
// Found a match but it was an existing non-menu item, so our menu
// structure is invalid.
//TODO consider mangling the IJ2 menu name instead...
throw new IllegalArgumentException("Not a menu: " + currentLabel);
}
}
// An existing entry in the parent menu was not found, so we need to
// create a new entry.
final Menu menu = new Menu(currentLabel);
parent.insert(menu, getIndex(parent, menu.getLabel()));
structure.put(currentLabel, menu);
return menu;
}
}
/**
* Evaluates the specified macro.
*
* @param macro the macro to evaluate
* @return the return value
*/
public String runMacro(final String macro) {
return IJ.runMacro(macro);
}
/**
* Evaluates the specified macro.
*
* @param path the macro file to evaluate
* @param arg the macro argument
* @return the return value
*/
public String runMacroFile(final String path, final String arg) {
return IJ.runMacroFile(path, arg);
}
/**
* Opens an image using ImageJ 1.x.
*
* @param path the image file to open
* @return the image
*/
public Object openImage(final String path) {
return IJ.openImage(path);
}
/**
* Opens a path using ImageJ 1.x, bypassing the (javassisted) IJ utility
* class.
*
* @param path the image file to open
*/
public void openPathDirectly(final String path) {
new Opener().open(path);
}
/**
* Enables or disables ImageJ 1.x' debug mode.
*
* @param debug whether to show debug messages or not
*/
public void setDebugMode(final boolean debug) {
IJ.debugMode = debug;
}
}
|
package net.imagej.ops.copy;
import net.imagej.ops.AbstractHybridOp;
import net.imagej.ops.ComputerOp;
import net.imagej.ops.Contingent;
import net.imagej.ops.FunctionOp;
import net.imagej.ops.OpService;
import net.imagej.ops.Ops;
import net.imglib2.img.Img;
import net.imglib2.type.NativeType;
import net.imglib2.util.Intervals;
import org.scijava.plugin.Parameter;
import org.scijava.plugin.Plugin;
/**
* Copying {@link Img} into another {@link Img}.
* Exists mainly for convenience reasons.
*
* @author Christian Dietz, University of Konstanz
* @param <T>
*/
@Plugin(type = Ops.Copy.Img.class)
public class CopyImg<T extends NativeType<T>> extends
AbstractHybridOp<Img<T>, Img<T>> implements Ops.Copy.Img, Contingent {
@Parameter
private OpService ops;
private ComputerOp<Iterable<T>, Iterable<T>> copyComputer;
private FunctionOp<Img<T>, Img<T>> createFunc;
@SuppressWarnings({ "rawtypes", "unchecked" })
@Override
public void initialize() {
copyComputer = (ComputerOp)ops.computer(CopyIterableInterval.class, in(), in());
createFunc = (FunctionOp) ops().function(Ops.Create.Img.class, Img.class,
in());
}
@Override
public Img<T> createOutput(final Img<T> input) {
return createFunc.compute(input);
}
@Override
public void compute(final Img<T> input, final Img<T> output) {
copyComputer.compute(input, output);
}
@Override
public boolean conforms() {
if (out() != null) {
return Intervals.equalDimensions(in(), out());
}
return true;
}
}
|
package org.basex.query;
import static org.basex.query.QueryText.*;
import static org.basex.query.util.Err.*;
import static org.basex.util.Token.*;
import static org.basex.util.ft.FTFlag.*;
import java.io.*;
import java.util.*;
import org.basex.core.*;
import org.basex.io.*;
import org.basex.io.serial.*;
import org.basex.query.expr.*;
import org.basex.query.expr.CmpG.OpG;
import org.basex.query.expr.CmpN.OpN;
import org.basex.query.expr.CmpV.OpV;
import org.basex.query.expr.Expr.*;
import org.basex.query.expr.Context;
import org.basex.query.expr.List;
import org.basex.query.flwor.*;
import org.basex.query.ft.*;
import org.basex.query.func.*;
import org.basex.query.item.*;
import org.basex.query.item.SeqType.Occ;
import org.basex.query.iter.*;
import org.basex.query.path.*;
import org.basex.query.up.expr.*;
import org.basex.query.util.*;
import org.basex.query.util.format.*;
import org.basex.util.*;
import org.basex.util.ft.*;
import org.basex.util.hash.*;
import org.basex.util.list.*;
public class QueryParser extends InputParser {
/** QName check: URI is mandatory. */
private static final byte[] URICHECK = {};
/** QName check: skip namespace check. */
private static final byte[] SKIPCHECK = {};
/** Reserved function names (sorted). */
private static final byte[][] KEYWORDS = {
NodeType.ATT.string(), NodeType.COM.string(), NodeType.DOC.string(),
NodeType.ELM.string(), AtomType.EMP.string(), FuncType.ANY_FUN.string(),
token(IF), AtomType.ITEM.string(),
NodeType.NSP.string(), NodeType.NOD.string(), NodeType.PI.string(),
token(SCHEMA_ATTRIBUTE), token(SCHEMA_ELEMENT), token(SWITCH),
NodeType.TXT.string(), token(TYPESWITCH)
};
/** Query context. */
final QueryContext ctx;
/** Temporary token builder. */
private final TokenBuilder tok = new TokenBuilder();
/** Modules loaded by the current file. */
private final TokenList modules = new TokenList();
/** Name of current module. */
private QNm module;
/** Alternative error output. */
private Err alter;
/** Alternative error description. */
private QNm alterFunc;
/** Alternative position. */
private int ap;
/** Declared serialization options. */
private final StringList serial = new StringList();
/** Declaration flag. */
private boolean declElem;
/** Declaration flag. */
private boolean declFunc;
/** Declaration flag. */
private boolean declColl;
/** Declaration flag. */
private boolean declConstr;
/** Declaration flag. */
private boolean declSpaces;
/** Declaration flag. */
private boolean declOrder;
/** Declaration flag. */
private boolean declReval;
/** Declaration flag. */
private boolean declGreat;
/** Declaration flag. */
private boolean declPres;
/** Declaration flag. */
private boolean declBase;
/** Declaration flag. */
private boolean declItem;
/** Declaration flag. */
private boolean declVars;
/** Cached QNames. */
private final ArrayList<QNmCheck> names = new ArrayList<QNmCheck>();
/**
* Constructor.
* @param in input
* @param c query context
* @throws QueryException query exception
*/
public QueryParser(final String in, final QueryContext c) throws QueryException {
super(in);
ctx = c;
// parse pre-defined external variables
final String bind = ctx.context.prop.get(Prop.BINDINGS).trim();
final StringBuilder key = new StringBuilder();
final StringBuilder val = new StringBuilder();
boolean first = true;
final int sl = bind.length();
for(int s = 0; s < sl; s++) {
final char ch = bind.charAt(s);
if(first) {
if(ch == '=') {
first = false;
} else {
key.append(ch);
}
} else {
if(ch == ',') {
if(s + 1 == sl || bind.charAt(s + 1) != ',') {
bind(key, val);
key.setLength(0);
val.setLength(0);
first = true;
continue;
}
// commas are escaped by a second comma
s++;
}
val.append(ch);
}
}
bind(key, val);
}
/**
* Binds the specified variable.
* If a URI is specified, the query is treated as a module.
* @param key key
* @param val value
* @throws QueryException query exception
*/
private void bind(final StringBuilder key, final StringBuilder val)
throws QueryException {
final String k = key.toString().trim();
if(!k.isEmpty()) ctx.bind(k, new Atm(val.toString()), null);
}
/**
* Parses the specified query or module.
* If the specified uri is {@code null}, the query is parsed as main module.
* @param uri module uri.
* @return resulting expression, or the name of the module
* @throws QueryException query exception
*/
public final Expr parse(final byte[] uri) throws QueryException {
file(ctx.sc.baseIO(), ctx.context);
if(!more()) error(QUERYEMPTY);
// checks if the query string contains invalid characters
for(int i = 0; i < il;) {
// only retrieve code points for large character codes (faster)
int cp = input.charAt(i);
final boolean hs = cp >= Character.MIN_HIGH_SURROGATE;
if(hs) cp = input.codePointAt(i);
if(!XMLToken.valid(cp)) {
ip = i;
error(QUERYINV, cp);
}
i += hs ? Character.charCount(cp) : 1;
}
final Expr expr = module(uri);
if(more()) {
if(alter != null) error();
final String rest = rest();
ip++;
if(uri != null) error(MODEXPR, rest);
error(QUERYEND, rest);
}
// completes the parsing step
assignURI(0);
ctx.funcs.check();
ctx.vars.checkUp();
if(ctx.sc.nsElem != null) ctx.sc.ns.add(EMPTY, ctx.sc.nsElem, null);
// set default decimal format
final byte[] empty = new QNm(EMPTY).eqname();
if(ctx.sc.decFormats.get(empty) == null) {
ctx.sc.decFormats.add(empty, new DecFormatter());
}
return expr;
}
/**
* Parses the specified query and starts with the "Module" rule.
* If the specified uri is {@code null}, the query is parsed as main module.
* @param u module uri
* @return resulting expression
* @throws QueryException query exception
*/
public final Expr module(final byte[] u) throws QueryException {
try {
Expr expr = null;
versionDecl();
if(u == null) {
final int i = ip;
if(wsConsumeWs(MODULE, NSPACE, null)) error(MAINMOD);
ip = i;
expr = mainModule();
if(expr == null) {
if(alter != null) error();
else error(EXPREMPTY);
}
} else {
expr = moduleDecl(u);
}
return expr;
} catch(final QueryException ex) {
mark();
ex.pos(this);
throw ex;
}
}
/**
* Parses the "VersionDecl" rule.
* @throws QueryException query exception
*/
private void versionDecl() throws QueryException {
final int i = ip;
if(!wsConsumeWs(XQUERY)) return;
final boolean version = wsConsumeWs(VERSION);
if(version) {
// parse xquery version
final String ver = string(stringLiteral());
if(ver.equals(XQ10)) ctx.xquery3 = false;
else if(eq(ver, XQ11, XQ30)) ctx.xquery3 = true;
else error(XQUERYVER, ver);
}
// parse xquery encoding (ignored, as input always comes in as string)
if((version || ctx.xquery3) && wsConsumeWs(ENCODING)) {
final String enc = string(stringLiteral());
if(!supported(enc)) error(XQUERYENC2, enc);
} else if(!version) {
ip = i;
return;
}
wsCheck(";");
}
/**
* Parses the "MainModule" rule.
* Parses the "Setter" rule.
* Parses the "QueryBody (= Expr)" rule.
* @return query expression
* @throws QueryException query exception
*/
private Expr mainModule() throws QueryException {
prolog1();
prolog2();
return expr();
}
/**
* Parses the "ModuleDecl" rule.
* @param u module uri (may be empty)
* @return name of module
* @throws QueryException query exception
*/
private QNm moduleDecl(final byte[] u) throws QueryException {
wsCheck(MODULE);
wsCheck(NSPACE);
skipWS();
final byte[] name = ncName(XPNAME);
wsCheck(IS);
final byte[] uri = stringLiteral();
if(uri.length == 0) error(NSMODURI);
module = new QNm(name, uri);
ctx.sc.ns.add(name, uri, info());
skipWS();
check(';');
prolog1();
prolog2();
// check if import and declaration uri match
// skip test if module has not been imported (in this case, URI is empty)
if(u.length != 0 && !eq(u, uri)) error(WRONGMODULE, module.uri(), file);
return module;
}
/**
* Parses the "Prolog" rule.
* Parses the "Setter" rule.
* @throws QueryException query exception
*/
private void prolog1() throws QueryException {
while(true) {
final int i = ip;
if(wsConsumeWs(DECLARE)) {
if(wsConsumeWs(DEFAULT)) {
if(!defaultNamespaceDecl() && !defaultCollationDecl() &&
!emptyOrderDecl() && !(ctx.xquery3 && decimalFormatDecl(true)))
error(DECLINCOMPLETE);
} else if(wsConsumeWs(BOUNDARY_SPACE)) {
boundarySpaceDecl();
} else if(wsConsumeWs(BASE_URI)) {
baseURIDecl();
} else if(wsConsumeWs(CONSTRUCTION)) {
constructionDecl();
} else if(wsConsumeWs(ORDERING)) {
orderingModeDecl();
} else if(wsConsumeWs(REVALIDATION)) {
revalidationDecl();
} else if(wsConsumeWs(COPY_NAMESPACES)) {
copyNamespacesDecl();
} else if(ctx.xquery3 && wsConsumeWs(DECIMAL_FORMAT)) {
decimalFormatDecl(false);
} else if(wsConsumeWs(NSPACE)) {
namespaceDecl();
} else if(wsConsumeWs(FT_OPTION)) {
final FTOpt fto = new FTOpt();
while(ftMatchOption(fto));
ctx.ftOpt().copy(fto);
} else {
ip = i;
return;
}
} else if(wsConsumeWs(IMPORT)) {
if(wsConsumeWs(SCHEMA)) {
schemaImport();
} else if(wsConsumeWs(MODULE)) {
moduleImport();
} else {
ip = i;
return;
}
} else {
return;
}
skipWS();
check(';');
}
}
/**
* Parses the "Prolog" rule.
* @throws QueryException query exception
*/
private void prolog2() throws QueryException {
while(true) {
final int i = ip;
if(!wsConsumeWs(DECLARE)) return;
if(ctx.xquery3 && wsConsumeWs(CONTEXT)) {
contextItemDecl();
} else if(wsConsumeWs(OPTION)) {
optionDecl();
} else if(wsConsumeWs(DEFAULT)) {
error(PROLOGORDER);
} else {
final Ann ann = new Ann();
while(true) {
if(wsConsumeWs(UPDATING)) {
addAnnotation(ann, Ann.UPDATING, Empty.SEQ);
} else if(ctx.xquery3 && consume('%')) {
annotation(ann);
} else {
break;
}
}
if(wsConsumeWs(VARIABLE)) {
// variables cannot be updating
if(ann.contains(Ann.UPDATING)) error(UPDATINGVAR);
varDecl(ann);
} else if(wsConsumeWs(FUNCTION)) {
functionDecl(ann);
} else if(!ann.isEmpty()) {
error(VARFUNC);
} else {
ip = i;
return;
}
}
skipWS();
check(';');
}
}
/**
* Parses the "Annotation" rule.
* @return annotations
* @throws QueryException query exception
*/
private Ann annotations() throws QueryException {
final Ann ann = new Ann();
while(wsConsume("%")) annotation(ann);
skipWS();
return ann;
}
/**
* Parses a single annotation.
* @param ann annotations
* @throws QueryException query exception
*/
private void annotation(final Ann ann) throws QueryException {
final QNm name = eQName(QNAMEINV, ctx.sc.nsFunc);
final ValueBuilder vb = new ValueBuilder(1);
if(wsConsumeWs(PAR1)) {
do {
final Item it = literal();
if(it == null) error(ANNVALUE);
vb.add(it);
} while(wsConsumeWs(COMMA));
wsCheck(PAR2);
}
skipWS();
addAnnotation(ann, name, vb.value());
}
/**
* Adds a single annotation.
* @param ann annotations
* @param name name
* @param value value
* @throws QueryException query exception
*/
private void addAnnotation(final Ann ann, final QNm name, final Value value)
throws QueryException {
if(name.eq(Ann.UPDATING)) {
if(ann.contains(Ann.UPDATING)) error(DUPLUPD);
} else if(name.eq(Ann.PUBLIC) || name.eq(Ann.PRIVATE)) {
// only one visibility modifier allowed
if(ann.contains(Ann.PUBLIC) || ann.contains(Ann.PRIVATE)) error(DUPLVIS);
} else if(NSGlobal.reserved(name.uri())) {
// no global namespaces allowed
error(ANNRES, name);
}
ann.add(name, value);
}
/**
* Parses the "NamespaceDecl" rule.
* @throws QueryException query exception
*/
private void namespaceDecl() throws QueryException {
final byte[] pref = ncName(XPNAME);
wsCheck(IS);
final byte[] uri = stringLiteral();
if(ctx.sc.ns.staticURI(pref) != null) error(DUPLNSDECL, pref);
ctx.sc.ns.add(pref, uri, info());
}
/**
* Parses the "RevalidationDecl" rule.
* @throws QueryException query exception
*/
private void revalidationDecl() throws QueryException {
if(declReval) error(DUPLREVAL);
declReval = true;
if(wsConsumeWs(STRICT) || wsConsumeWs(LAX)) error(NOREVAL);
wsCheck(SKIP);
}
/**
* Parses the "BoundarySpaceDecl" rule.
* @throws QueryException query exception
*/
private void boundarySpaceDecl() throws QueryException {
if(declSpaces) error(DUPLBOUND);
declSpaces = true;
final boolean spaces = wsConsumeWs(PRESERVE);
if(!spaces) wsCheck(STRIP);
ctx.sc.spaces = spaces;
}
/**
* Parses the "DefaultNamespaceDecl" rule.
* @return true if declaration was found
* @throws QueryException query exception
*/
private boolean defaultNamespaceDecl() throws QueryException {
final boolean elem = wsConsumeWs(ELEMENT);
if(!elem && !wsConsumeWs(FUNCTION)) return false;
wsCheck(NSPACE);
final byte[] uri = stringLiteral();
if(eq(XMLURI, uri)) error(BINDXMLURI, uri, XML);
if(eq(XMLNSURI, uri)) error(BINDXMLURI, uri, XMLNS);
if(elem) {
if(declElem) error(DUPLNS);
declElem = true;
ctx.sc.nsElem = uri.length == 0 ? null : uri;
} else {
if(declFunc) error(DUPLNS);
declFunc = true;
ctx.sc.nsFunc = uri.length == 0 ? null : uri;
}
return true;
}
/**
* Parses the "OptionDecl" rule.
* @throws QueryException query exception
*/
private void optionDecl() throws QueryException {
skipWS();
final QNm name = eQName(QNAMEINV, URICHECK);
final byte[] val = stringLiteral();
if(ctx.xquery3 && eq(name.prefix(), OUTPUT)) {
// output declaration
final String key = string(name.local());
if(module != null) error(MODOUT);
if(ctx.serProp == null) ctx.serProp = new SerializerProp();
if(ctx.serProp.get(key) == null) error(OUTWHICH, key);
if(serial.contains(key)) error(OUTDUPL, key);
ctx.serProp.set(key, string(val));
serial.add(key);
} else if(eq(name.prefix(), DB)) {
// project-specific declaration
final String key = string(uc(name.local()));
final Object obj = ctx.context.prop.get(key);
if(obj == null) error(NOOPTION, key);
// cache old value (to be reset after query evaluation)
ctx.globalOpt.put(key, obj);
ctx.dbOptions.put(key, string(val));
}
// ignore unknown options
}
/**
* Parses the "OrderingModeDecl" rule.
* @throws QueryException query exception
*/
private void orderingModeDecl() throws QueryException {
if(declOrder) error(DUPLORD);
declOrder = true;
ctx.sc.ordered = wsConsumeWs(ORDERED);
if(!ctx.sc.ordered) wsCheck(UNORDERED);
}
/**
* Parses the "emptyOrderDecl" rule.
* @return true if declaration was found
* @throws QueryException query exception
*/
private boolean emptyOrderDecl() throws QueryException {
if(!wsConsumeWs(ORDER)) return false;
wsCheck(EMPTYORD);
if(declGreat) error(DUPLORDEMP);
declGreat = true;
ctx.sc.orderGreatest = wsConsumeWs(GREATEST);
if(!ctx.sc.orderGreatest) wsCheck(LEAST);
return true;
}
/**
* Parses the "copyNamespacesDecl" rule.
* Parses the "PreserveMode" rule.
* Parses the "InheritMode" rule.
* @throws QueryException query exception
*/
private void copyNamespacesDecl() throws QueryException {
if(declPres) error(DUPLCOPYNS);
declPres = true;
ctx.sc.nsPreserve = wsConsumeWs(PRESERVE);
if(!ctx.sc.nsPreserve) wsCheck(NO_PRESERVE);
wsCheck(COMMA);
ctx.sc.nsInherit = wsConsumeWs(INHERIT);
if(!ctx.sc.nsInherit) wsCheck(NO_INHERIT);
}
/**
* Parses the "DecimalFormatDecl" rule.
* @param def default flag
* @return true if declaration was found
* @throws QueryException query exception
*/
private boolean decimalFormatDecl(final boolean def) throws QueryException {
if(def && !wsConsumeWs(DECIMAL_FORMAT)) return false;
// use empty name for default declaration
final QNm name = def ? new QNm() : eQName(QNAMEINV, null);
// check if format has already been declared
if(ctx.sc.decFormats.get(name.eqname()) != null) error(DECDUPL);
// create new format
final HashMap<String, String> map = new HashMap<String, String>();
// collect all property declarations
int n;
do {
n = map.size();
skipWS();
final String prop = string(ncName(null));
for(final String s : DECFORMATS) {
if(!prop.equals(s)) continue;
if(map.get(s) != null) error(DECDUPLPROP, s);
wsCheck(IS);
map.put(s, string(stringLiteral()));
break;
}
if(map.isEmpty()) error(NODECLFORM, prop);
} while(n != map.size());
// completes the format declaration
ctx.sc.decFormats.add(name.eqname(), new DecFormatter(info(), map));
return true;
}
/**
* Parses the "DefaultCollationDecl" rule.
* @return query expression
* @throws QueryException query exception
*/
private boolean defaultCollationDecl() throws QueryException {
if(!wsConsumeWs(COLLATION)) return false;
if(declColl) error(DUPLCOLL);
declColl = true;
final byte[] cl = ctx.sc.baseURI().resolve(Uri.uri(stringLiteral())).string();
if(!eq(URLCOLL, cl)) error(COLLWHICH, cl);
return true;
}
/**
* Parses the "BaseURIDecl" rule.
* @throws QueryException query exception
*/
private void baseURIDecl() throws QueryException {
if(declBase) error(DUPLBASE);
declBase = true;
final byte[] base = stringLiteral();
if(base.length != 0) ctx.sc.baseURI(string(base));
}
/**
* Parses the "SchemaImport" rule.
* Parses the "SchemaPrefix" rule.
* @throws QueryException query exception
*/
private void schemaImport() throws QueryException {
if(wsConsumeWs(NSPACE)) {
ncName(XPNAME);
wsCheck(IS);
} else if(wsConsumeWs(DEFAULT)) {
wsCheck(ELEMENT);
wsCheck(NSPACE);
}
final byte[] ns = stringLiteral();
if(ns.length == 0) error(NSEMPTY);
if(wsConsumeWs(AT)) {
do stringLiteral(); while(wsConsumeWs(COMMA));
}
error(IMPLSCHEMA);
}
/**
* Parses the "ModuleImport" rule.
* @throws QueryException query exception
*/
private void moduleImport() throws QueryException {
byte[] ns = EMPTY;
if(wsConsumeWs(NSPACE)) {
ns = ncName(XPNAME);
wsCheck(IS);
}
final byte[] uri = trim(stringLiteral());
if(uri.length == 0) error(NSMODURI);
if(modules.contains(uri)) error(DUPLMODULE, uri);
modules.add(uri);
// add non-default namespace
if(ns != EMPTY) ctx.sc.ns.add(ns, uri, info());
try {
// check modules at specified locations
if(wsConsumeWs(AT)) {
do {
module(stringLiteral(), uri);
} while(wsConsumeWs(COMMA));
return;
}
// check pre-declared module files
final byte[] path = ctx.modDeclared.get(uri);
if(path != null) {
module(path, uri);
return;
}
// check built-in modules
for(final byte[] u : MODULES) if(eq(uri, u)) return;
// resolve module uri
if(ctx.modules.addImport(uri, info(), this)) return;
error(NOMODULE, uri);
} catch(final StackOverflowError ex) {
Util.debug(ex);
error(CIRCMODULE);
}
}
/**
* Parses the specified module.
* @param path file path
* @param uri module uri
* @throws QueryException query exception
*/
public void module(final byte[] path, final byte[] uri) throws QueryException {
// get absolute path
final IO io = ctx.sc.io(string(path));
final byte[] p = token(io.path());
// check if module has already been parsed
final byte[] u = ctx.modParsed.get(p);
if(u != null) {
if(!eq(uri, u)) error(WRONGMODULE, uri,
ctx.context.user.has(Perm.ADMIN) ? io.path() : io.name());
return;
}
ctx.modParsed.add(p, uri);
// read module
String qu = null;
try {
qu = string(io.read());
} catch(final IOException ex) {
error(NOMODULEFILE, ctx.context.user.has(Perm.ADMIN) ? io.path() : io.name());
}
final StaticContext sc = ctx.sc;
ctx.sc = new StaticContext();
ctx.sc.baseURI(io.path());
new QueryParser(qu, ctx).parse(uri);
ctx.sc = sc;
}
/**
* Parses the "ContextItemDecl" rule.
* @throws QueryException query exception
*/
private void contextItemDecl() throws QueryException {
wsCheck(ITEMM);
if(declItem) error(DUPLITEM);
declItem = true;
if(module != null) error(DECITEM);
final SeqType st = optAsType();
if(st != null && st.type == AtomType.EMP) error(NOTYPE, st);
ctx.sc.initType = st;
if(!wsConsumeWs(EXTERNAL)) wsCheck(ASSIGN);
else if(!wsConsumeWs(ASSIGN)) return;
ctx.ctxItem = check(single(), NOVARDECL);
if(ctx.ctxItem.uses(Use.UPD)) UPCTX.thrw(info(), ctx.ctxItem);
}
/**
* Parses the "VarDecl" rule.
* @param ann annotations
* @throws QueryException query exception
*/
private void varDecl(final Ann ann) throws QueryException {
final Var v = typedVar(ann);
if(module != null && !eq(v.name.uri(), module.uri())) error(MODNS, v);
// check if variable has already been declared
final Var old = ctx.vars.get(v.name);
// throw no error if a variable has been externally bound
if(old != null && old.declared) error(VARDEFINE, old);
(old != null ? old : v).declared = true;
if(wsConsumeWs(EXTERNAL)) {
// bind value with new type
if(old != null && v.type != null) old.reset(v.type, ctx);
// bind default value
if(ctx.xquery3 && wsConsumeWs(ASSIGN)) {
v.bind(check(single(), NOVARDECL), ctx);
}
} else {
wsCheck(ASSIGN);
v.bind(check(single(), NOVARDECL), ctx);
}
// bind variable if not done yet
if(old == null) ctx.vars.updateGlobal(v);
}
/**
* Parses a variable declaration with optional type.
* @param ann annotations
* @return parsed variable
* @throws QueryException query exception
*/
private Var typedVar(final Ann ann) throws QueryException {
return Var.create(ctx, info(), varName(), optAsType(), ann);
}
/**
* Parses an optional SeqType declaration.
* @return type if preceded by {@code as}, {@code null} otherwise
* @throws QueryException query exception
*/
private SeqType optAsType() throws QueryException {
return wsConsumeWs(AS) ? sequenceType() : null;
}
/**
* Parses the "ConstructionDecl" rule.
* @throws QueryException query exception
*/
private void constructionDecl() throws QueryException {
if(declConstr) error(DUPLCONS);
declConstr = true;
ctx.sc.strip = wsConsumeWs(STRIP);
if(!ctx.sc.strip) wsCheck(PRESERVE);
}
/**
* Parses the "FunctionDecl" rule.
* @param ann annotations
* @throws QueryException query exception
*/
private void functionDecl(final Ann ann) throws QueryException {
final QNm name = eQName(FUNCNAME, ctx.sc.nsFunc);
if(keyword(name)) error(RESERVED, name);
if(module != null && !eq(name.uri(), module.uri())) error(MODNS, name);
wsCheck(PAR1);
final VarStack vl = ctx.vars.cache(4);
final Var[] args = paramList();
wsCheck(PAR2);
final UserFunc func = new UserFunc(info(), name, args, optAsType(), ann, true);
if(func.updating) ctx.updating(true);
ctx.funcs.add(func, info());
if(!wsConsumeWs(EXTERNAL)) func.expr = enclosed(NOFUNBODY);
ctx.vars.reset(vl);
}
/**
* Checks if the specified name equals reserved function names.
* @param name name to be checked
* @return result of check
*/
private static boolean keyword(final QNm name) {
if(name.hasPrefix()) return false;
final byte[] str = name.string();
for(final byte[] key : KEYWORDS) if(eq(key, str)) return true;
return false;
}
/**
* Parses a ParamList.
* @return declared variables
* @throws QueryException query exception
*/
private Var[] paramList() throws QueryException {
Var[] args = { };
skipWS();
while(true) {
if(curr() != '$') {
if(args.length == 0) break;
check('$');
}
final Var var = typedVar(null);
ctx.vars.add(var);
for(final Var v : args)
if(v.name.eq(var.name)) error(FUNCDUPL, var);
args = Array.add(args, var);
if(!consume(',')) break;
skipWS();
}
return args;
}
/**
* Parses the "EnclosedExpr" rule.
* @param err error message
* @return query expression
* @throws QueryException query exception
*/
private Expr enclosed(final Err err) throws QueryException {
wsCheck(BRACE1);
final Expr e = check(expr(), err);
wsCheck(BRACE2);
return e;
}
/**
* Parses the "Expr" rule.
* @return query expression
* @throws QueryException query exception
*/
private Expr expr() throws QueryException {
final Expr e = single();
if(e == null) {
if(more()) return null;
if(alter != null) error();
else error(NOEXPR);
}
if(!wsConsume(COMMA)) return e;
final ExprList el = new ExprList(e);
do add(el, single()); while(wsConsume(COMMA));
return new List(info(), el.finish());
}
/**
* Parses the "ExprSingle" rule.
* @return query expression
* @throws QueryException query exception
*/
private Expr single() throws QueryException {
alter = null;
Expr e = flwor();
if(e == null) e = quantified();
if(e == null) e = switchh();
if(e == null) e = typeswitch();
if(e == null) e = iff();
if(e == null) e = tryCatch();
if(e == null) e = insert();
if(e == null) e = deletee();
if(e == null) e = rename();
if(e == null) e = replace();
if(e == null) e = transform();
if(e == null) e = or();
return e;
}
/**
* Parses the "FLWORExpr" rule.
* Parses the "WhereClause" rule.
* Parses the "OrderByClause" rule.
* Parses the "OrderSpecList" rule.
* Parses the "GroupByClause" rule.
* @return query expression
* @throws QueryException query exception
*/
private Expr flwor() throws QueryException {
// XQuery30: tumbling window, sliding window, count, allowing empty
// (still to be parsed and implemented)
final int s = ctx.vars.size();
final ForLet[] fl = forLet();
if(fl == null) return null;
Expr where = null;
if(wsConsumeWs(WHERE)) {
ap = ip;
where = check(single(), NOWHERE);
alter = NOWHERE;
}
Group group = null;
if(ctx.xquery3 && wsConsumeWs(GROUP)) {
wsCheck(BY);
ap = ip;
Group.Spec[] grp = null;
do grp = groupSpec(fl, grp); while(wsConsume(COMMA));
// find all non-grouping variables that aren't shadowed
final ArrayList<Var> ng = new ArrayList<Var>();
final TokenSet set = new TokenSet();
for(final Group.Spec spec : grp) set.add(spec.grp.name.eqname());
for(int i = fl.length; --i >= 0;) {
for(final Var v : fl[i].vars()) {
final byte[] eqn = v.name.eqname();
if(!set.contains(eqn)) {
ng.add(v);
set.add(eqn);
}
}
}
// add new copies for all non-grouping variables
final Var[] ngrp = new Var[ng.size()];
for(int i = ng.size(); --i >= 0;) {
final Var v = ng.get(i);
// if one groups variables such as $x as xs:integer, then the resulting
// sequence isn't compatible with the type and can't be assigned
ngrp[i] = Var.create(ctx, info(), v.name, v.type != null
&& v.type.one() ? SeqType.get(v.type.type, Occ.ONE_MORE) : null, null);
ctx.vars.add(ngrp[i]);
}
group = new Group(grp[0].info, grp,
new Var[][] { ng.toArray(new Var[ng.size()]), ngrp });
alter = GRPBY;
}
Order order = null;
final boolean stable = wsConsumeWs(STABLE);
if(stable) wsCheck(ORDER);
if(stable || wsConsumeWs(ORDER)) {
wsCheck(BY);
ap = ip;
OrderBy[] ob = null;
do ob = orderSpec(ob); while(wsConsume(COMMA));
// don't sort if all order-by clauses are empty
if(ob != null) {
ob = Array.add(ob, new OrderByStable(info()));
order = new Order(ob[0].info, ob);
}
alter = ORDERBY;
}
if(!wsConsumeWs(RETURN)) {
if(alter != null) error();
error(where == null ? FLWORWHERE : order == null ? FLWORORD : FLWORRET);
}
final Expr ret = check(single(), NORETURN);
ctx.vars.size(s);
return GFLWOR.get(fl, where, order, group, ret, info());
}
/**
* Parses the "ForClause" rule.
* Parses the "PositionalVar" rule.
* Parses the "LetClause" rule.
* Parses the "FTScoreVar" rule.
* @return query expression
* @throws QueryException query exception
*/
private ForLet[] forLet() throws QueryException {
ForLet[] fl = null;
boolean comma = false;
while(true) {
final boolean fr = wsConsumeWs(FOR, DOLLAR, NOFOR);
boolean score = !fr && wsConsumeWs(LET, SCORE, NOLET);
if(score) wsCheck(SCORE);
else if(!fr && !wsConsumeWs(LET, DOLLAR, NOLET)) return fl;
do {
if(comma && !fr) score = wsConsumeWs(SCORE);
final QNm name = varName();
final SeqType type = score ? SeqType.DBL : optAsType();
final Var var = Var.create(ctx, info(), name, type, null);
final Var ps = fr && wsConsumeWs(AT) ? Var.create(ctx, info(),
varName(), SeqType.ITR, null) : null;
final Var sc = fr && wsConsumeWs(SCORE) ? Var.create(ctx, info(),
varName(), SeqType.DBL, null) : null;
wsCheck(fr ? IN : ASSIGN);
final Expr e = check(single(), NOVARDECL);
ctx.vars.add(var);
if(ps != null) {
if(name.eq(ps.name)) error(DUPLVAR, var);
ctx.vars.add(ps);
}
if(sc != null) {
if(name.eq(sc.name)) error(DUPLVAR, var);
if(ps != null && ps.name.eq(sc.name)) error(DUPLVAR, ps);
ctx.vars.add(sc);
}
fl = fl == null ? new ForLet[1] : Arrays.copyOf(fl, fl.length + 1);
fl[fl.length - 1] = fr ? new For(info(), e, var, ps, sc) : new Let(
info(), e, var, score);
score = false;
comma = true;
} while(wsConsume(COMMA));
comma = false;
}
}
/**
* Parses the "OrderSpec" rule.
* Parses the "OrderModifier" rule.
*
* Empty order specs are ignored, {@code order} is then returned unchanged.
* @param order order array
* @return new order array
* @throws QueryException query exception
*/
private OrderBy[] orderSpec(final OrderBy[] order) throws QueryException {
final Expr e = check(single(), ORDERBY);
boolean desc = false;
if(!wsConsumeWs(ASCENDING)) desc = wsConsumeWs(DESCENDING);
boolean least = !ctx.sc.orderGreatest;
if(wsConsumeWs(EMPTYORD)) {
least = !wsConsumeWs(GREATEST);
if(least) wsCheck(LEAST);
}
if(wsConsumeWs(COLLATION)) {
final byte[] coll = stringLiteral();
if(!eq(URLCOLL, coll)) error(WHICHCOLL, coll);
}
if(e.isEmpty()) return order;
final OrderBy ord = new OrderByExpr(info(), e, desc, least);
return order == null ? new OrderBy[] { ord } : Array.add(order, ord);
}
/**
* Parses the "GroupingSpec" rule.
* @param fl for/let clauses
* @param group grouping specification
* @return new group array
* @throws QueryException query exception
*/
private Group.Spec[] groupSpec(final ForLet[] fl, final Group.Spec[] group)
throws QueryException {
final InputInfo ii = info();
final QNm name = varName();
final SeqType type = optAsType();
final Var var = Var.create(ctx, ii, name, type, null);
final Expr by;
if(type != null || wsConsume(ASSIGN)) {
if(type != null) wsCheck(ASSIGN);
by = check(single(), NOVARDECL);
} else {
final Var v = checkVar(var.name, GVARNOTDEFINED);
// the grouping variable has to be declared by the same FLWOR expression
boolean dec = false;
for(final ForLet f : fl) {
if(f.declares(v)) {
dec = true;
break;
}
}
if(!dec) throw error(GVARNOTDEFINED, v);
by = new VarRef(ii, v);
}
if(wsConsumeWs(COLLATION)) {
final byte[] coll = stringLiteral();
if(!eq(URLCOLL, coll)) throw error(WHICHCOLL, coll);
}
// add the new grouping var
ctx.vars.add(var);
final Group.Spec grp = new Group.Spec(ii, var, by);
return group == null ? new Group.Spec[] { grp } : Array.add(group, grp);
}
/**
* Parses the "QuantifiedExpr" rule.
* @return query expression
* @throws QueryException query exception
*/
private Expr quantified() throws QueryException {
final boolean some = wsConsumeWs(SOME, DOLLAR, NOSOME);
if(!some && !wsConsumeWs(EVERY, DOLLAR, NOSOME)) return null;
final int s = ctx.vars.size();
For[] fl = { };
do {
final Var var = typedVar(null);
wsCheck(IN);
final Expr e = check(single(), NOSOME);
ctx.vars.add(var);
fl = Array.add(fl, new For(info(), e, var));
} while(wsConsume(COMMA));
wsCheck(SATISFIES);
final Expr e = check(single(), NOSOME);
ctx.vars.size(s);
return new Quantifier(info(), fl, e, !some);
}
/**
* Parses the "SwitchExpr" rule.
* @return query expression
* @throws QueryException query exception
*/
private Expr switchh() throws QueryException {
if(!ctx.xquery3 || !wsConsumeWs(SWITCH, PAR1, TYPEPAR)) return null;
wsCheck(PAR1);
final Expr expr = check(expr(), NOSWITCH);
SwitchCase[] exprs = { };
wsCheck(PAR2);
// collect all cases
ExprList cases;
do {
cases = new ExprList(null);
while(wsConsumeWs(CASE)) add(cases, single());
if(cases.size() == 1) {
// add default case
if(exprs.length == 0) error(WRONGCHAR, CASE, found());
wsCheck(DEFAULT);
}
wsCheck(RETURN);
cases.set(0, single());
exprs = Array.add(exprs, new SwitchCase(info(), cases.finish()));
} while(cases.size() != 1);
return new Switch(info(), expr, exprs);
}
/**
* Parses the "TypeswitchExpr" rule.
* @return query expression
* @throws QueryException query exception
*/
private Expr typeswitch() throws QueryException {
if(!wsConsumeWs(TYPESWITCH, PAR1, TYPEPAR)) return null;
wsCheck(PAR1);
final Expr ts = check(expr(), NOTYPESWITCH);
wsCheck(PAR2);
TypeCase[] cases = { };
final int s = ctx.vars.size();
boolean cs;
do {
cs = wsConsumeWs(CASE);
if(!cs) wsCheck(DEFAULT);
skipWS();
QNm name = null;
if(curr('$')) {
name = varName();
if(cs) wsCheck(AS);
}
final Var v = Var.create(ctx, info(), name, cs ? sequenceType() : null, null);
if(name != null) ctx.vars.add(v);
wsCheck(RETURN);
final Expr ret = check(single(), NOTYPESWITCH);
cases = Array.add(cases, new TypeCase(info(), v, ret));
ctx.vars.size(s);
} while(cs);
if(cases.length == 1) error(NOTYPESWITCH);
return new TypeSwitch(info(), ts, cases);
}
/**
* Parses the "IfExpr" rule.
* @return query expression
* @throws QueryException query exception
*/
private Expr iff() throws QueryException {
if(!wsConsumeWs(IF, PAR1, IFPAR)) return null;
wsCheck(PAR1);
final Expr iff = check(expr(), NOIF);
wsCheck(PAR2);
if(!wsConsumeWs(THEN)) error(NOIF);
final Expr thn = check(single(), NOIF);
if(!wsConsumeWs(ELSE)) error(NOIF);
final Expr els = check(single(), NOIF);
return new If(info(), iff, thn, els);
}
/**
* Parses the "OrExpr" rule.
* @return query expression
* @throws QueryException query exception
*/
private Expr or() throws QueryException {
final Expr e = and();
if(!wsConsumeWs(OR)) return e;
final ExprList el = new ExprList(e);
do add(el, and()); while(wsConsumeWs(OR));
return new Or(info(), el.finish());
}
/**
* Parses the "AndExpr" rule.
* @return query expression
* @throws QueryException query exception
*/
private Expr and() throws QueryException {
final Expr e = comparison();
if(!wsConsumeWs(AND)) return e;
final ExprList el = new ExprList(e);
do add(el, comparison()); while(wsConsumeWs(AND));
return new And(info(), el.finish());
}
/**
* Parses the "ComparisonExpr" rule.
* @return query expression
* @throws QueryException query exception
*/
private Expr comparison() throws QueryException {
final Expr e = ftContains();
if(e != null) {
for(final OpV c : OpV.values()) if(wsConsumeWs(c.name))
return new CmpV(e, check(ftContains(), CMPEXPR), c, info());
for(final OpN c : OpN.values()) if(wsConsumeWs(c.name))
return new CmpN(e, check(ftContains(), CMPEXPR), c, info());
for(final OpG c : OpG.values()) if(wsConsumeWs(c.name))
return new CmpG(e, check(ftContains(), CMPEXPR), c, info());
}
return e;
}
/**
* Parses the "FTContainsExpr" rule.
* @return query expression
* @throws QueryException query exception
*/
private Expr ftContains() throws QueryException {
final Expr e = stringConcat();
final int i = ip;
// extensions to the official extension: "=>" and "<-"
if(consume('=') && consume('>') || consume('<') && consume('-')) {
skipWS();
} else if(!wsConsumeWs(CONTAINS) || !wsConsumeWs(TEXT)) {
ip = i;
return e;
}
final FTExpr select = ftSelection(false);
if(wsConsumeWs(WITHOUT)) {
wsCheck(CONTENT);
union();
error(FTIGNORE);
}
return new FTContains(e, select, info());
}
/**
* Parses the "StringConcatExpr" rule.
* @return query expression
* @throws QueryException query exception
*/
private Expr stringConcat() throws QueryException {
final Expr e = range();
if(e == null || !consume(CONCAT)) return e;
final ExprList el = new ExprList(e);
do add(el, range()); while(wsConsume(CONCAT));
return Function.CONCAT.get(info(), el.finish());
}
/**
* Parses the "RangeExpr" rule.
* @return query expression
* @throws QueryException query exception
*/
private Expr range() throws QueryException {
final Expr e = additive();
if(!wsConsumeWs(TO)) return e;
return new Range(info(), e, check(additive(), INCOMPLETE));
}
/**
* Parses the "AdditiveExpr" rule.
* @return query expression
* @throws QueryException query exception
*/
private Expr additive() throws QueryException {
Expr e = multiplicative();
while(e != null) {
final Calc c = consume('+') ? Calc.PLUS : consume('-') ? Calc.MINUS : null;
if(c == null) break;
e = new Arith(info(), e, check(multiplicative(), CALCEXPR), c);
}
return e;
}
/**
* Parses the "MultiplicativeExpr" rule.
* @return query expression
* @throws QueryException query exception
*/
private Expr multiplicative() throws QueryException {
Expr e = union();
while(e != null) {
final Calc c = consume('*') ? Calc.MULT : wsConsumeWs(DIV) ? Calc.DIV
: wsConsumeWs(IDIV) ? Calc.IDIV : wsConsumeWs(MOD) ? Calc.MOD : null;
if(c == null) break;
e = new Arith(info(), e, check(union(), CALCEXPR), c);
}
return e;
}
/**
* Parses the "UnionExpr" rule.
* @return query expression
* @throws QueryException query exception
*/
private Expr union() throws QueryException {
final Expr e = intersect();
if(e == null || !isUnion()) return e;
final ExprList el = new ExprList(e);
do add(el, intersect()); while(isUnion());
return new Union(info(), el.finish());
}
/**
* Checks if a union operator is found.
* @return result of check
* @throws QueryException query exception
*/
private boolean isUnion() throws QueryException {
if(wsConsumeWs(UNION)) return true;
final int i = ip;
if(consume(PIPE) && !consume(PIPE)) return true;
ip = i;
return false;
}
/**
* Parses the "IntersectExceptExpr" rule.
* @return query expression
* @throws QueryException query exception
*/
private Expr intersect() throws QueryException {
final Expr e = instanceoff();
if(wsConsumeWs(INTERSECT)) {
final ExprList el = new ExprList(e);
do add(el, instanceoff()); while(wsConsumeWs(INTERSECT));
return new InterSect(info(), el.finish());
}
if(wsConsumeWs(EXCEPT)) {
final ExprList el = new ExprList(e);
do add(el, instanceoff()); while(wsConsumeWs(EXCEPT));
return new Except(info(), el.finish());
}
return e;
}
/**
* Parses the "InstanceofExpr" rule.
* @return query expression
* @throws QueryException query exception
*/
private Expr instanceoff() throws QueryException {
final Expr e = treat();
if(!wsConsumeWs(INSTANCE)) return e;
wsCheck(OF);
return new Instance(info(), e, sequenceType());
}
/**
* Parses the "TreatExpr" rule.
* @return query expression
* @throws QueryException query exception
*/
private Expr treat() throws QueryException {
final Expr e = castable();
if(!wsConsumeWs(TREAT)) return e;
wsCheck(AS);
return new Treat(info(), e, sequenceType());
}
/**
* Parses the "CastableExpr" rule.
* @return query expression
* @throws QueryException query exception
*/
private Expr castable() throws QueryException {
final Expr e = cast();
if(!wsConsumeWs(CASTABLE)) return e;
wsCheck(AS);
return new Castable(info(), e, simpleType());
}
/**
* Parses the "CastExpr" rule.
* @return query expression
* @throws QueryException query exception
*/
private Expr cast() throws QueryException {
final Expr e = unary();
if(!wsConsumeWs(CAST)) return e;
wsCheck(AS);
return new Cast(info(), e, simpleType());
}
/**
* Parses the "UnaryExpr" rule.
* @return query expression
* @throws QueryException query exception
*/
private Expr unary() throws QueryException {
boolean minus = false;
boolean found = false;
do {
skipWS();
if(consume('-')) {
minus ^= true;
found = true;
} else if(consume('+')) {
found = true;
} else {
final Expr e = value();
return found ? new Unary(info(), check(e, EVALUNARY), minus) : e;
}
} while(true);
}
/**
* Parses the "ValueExpr" rule.
* @return query expression
* @throws QueryException query exception
*/
private Expr value() throws QueryException {
validate();
final Expr e = path();
return e != null ? e : extension();
}
/**
* Parses the "ValidateExpr" rule.
* @throws QueryException query exception
*/
private void validate() throws QueryException {
if(wsConsumeWs(VALIDATE)) {
if(!wsConsumeWs(STRICT) && !wsConsumeWs(LAX) && wsConsumeWs(TYPE)) {
final QNm qnm = eQName(QNAMEINV, SKIPCHECK);
names.add(new QNmCheck(qnm));
error(NOSCHEMA, qnm);
}
wsCheck(BRACE1);
check(single(), NOVALIDATE);
wsCheck(BRACE2);
error(IMPLVAL);
}
}
/**
* Parses the "ExtensionExpr" rule.
* @return query expression
* @throws QueryException query exception
*/
private Expr extension() throws QueryException {
final Pragma[] pragmas = pragma();
return pragmas == null ? null : new Extension(info(), pragmas, enclosed(NOPRAGMA));
}
/**
* Parses the "Pragma" rule.
* @return array of pragmas
* @throws QueryException query exception
*/
private Pragma[] pragma() throws QueryException {
if(!wsConsumeWs(PRAGMA)) return null;
final ArrayList<Pragma> el = new ArrayList<Pragma>();
do {
final QNm name = eQName(QNAMEINV, URICHECK);
char c = curr();
if(c != '
tok.reset();
while(c != '#' || next() != ')') {
if(c == 0) error(PRAGMAINV);
tok.add(consume());
c = curr();
}
el.add(new Pragma(name, tok.trim().finish()));
ip += 2;
} while(wsConsumeWs(PRAGMA));
return el.toArray(new Pragma[el.size()]);
}
/**
* Parses the "PathExpr" rule.
* @return query expression
* @throws QueryException query exception
*/
private Expr path() throws QueryException {
checkInit();
final ExprList el;
Expr root = null;
if(consume('/')) {
root = new Root(info());
el = new ExprList();
final Expr ex;
if(consume('/')) {
// two slashes: absolute descendant path
checkAxis(Axis.DESC);
add(el, descOrSelf());
mark();
ex = step();
if(ex == null) {
// two slashes, but no following step: error
if(more()) checkInit();
error(PATHMISS, found());
}
} else {
// one slash: absolute child path
checkAxis(Axis.CHILD);
mark();
ex = step();
// no more steps: return root expression
if(ex == null) return root;
}
add(el, ex);
relativePath(el);
} else {
// relative path (no preceding slash)
mark();
final Expr ex = step();
if(ex == null) return null;
// return non-step expression if no path or map operator follows
final boolean nostep = curr() != '/' && (curr() != '!' || next() == '=');
if(nostep && !(ex instanceof AxisStep)) return ex;
el = new ExprList();
if(ex instanceof AxisStep) add(el, ex);
else root = ex;
relativePath(el);
}
return Path.get(info(), root, el.finish());
}
/**
* Parses the "RelativePathExpr" rule.
* @param el expression list
* @throws QueryException query exception
*/
void relativePath(final ExprList el) throws QueryException {
while(true) {
boolean b = false;
if(consume('/')) {
if(consume('/')) {
add(el, descOrSelf());
checkAxis(Axis.DESC);
} else {
checkAxis(Axis.CHILD);
}
} else if(next() != '=' && consume('!')) {
b = true;
} else {
return;
}
mark();
Expr st = step();
if(st == null) error(PATHMISS, found());
if(b) st = new Bang(info(), st);
add(el, st);
}
}
/**
* Returns a standard descendant-or-self::node() step.
* @return step
*/
private AxisStep descOrSelf() {
return AxisStep.get(info(), Axis.DESCORSELF, Test.NOD);
}
// methods for query suggestions
/**
* Performs an optional check init.
*/
protected void checkInit() { }
/**
* Performs an optional axis check.
* @param axis axis
*/
@SuppressWarnings("unused")
protected void checkAxis(final Axis axis) { }
/**
* Performs an optional test check.
* @param test node test
* @param attr attribute flag
*/
@SuppressWarnings("unused")
protected void checkTest(final Test test, final boolean attr) { }
/**
* Checks a predicate.
* @param open open flag
*/
@SuppressWarnings("unused")
protected void checkPred(final boolean open) { }
/**
* Parses the "StepExpr" rule.
* @return query expression
* @throws QueryException query exception
*/
private Expr step() throws QueryException {
final Expr e = postfix();
return e != null ? e : axisStep();
}
/**
* Parses the "AxisStep" rule.
* @return query expression
* @throws QueryException query exception
*/
private AxisStep axisStep() throws QueryException {
Axis ax = null;
Test test = null;
if(wsConsume(DOT2)) {
ax = Axis.PARENT;
test = Test.NOD;
checkTest(test, false);
} else if(consume('@')) {
ax = Axis.ATTR;
test = nodeTest(true, true);
checkTest(test, true);
if(test == null) {
--ip;
error(NOATTNAME);
}
} else {
for(final Axis a : Axis.values()) {
final int i = ip;
if(!wsConsumeWs(a.name)) continue;
alter = NOLOCSTEP;
if(wsConsumeWs(COLS)) {
ap = ip;
ax = a;
test = nodeTest(a == Axis.ATTR, true);
checkTest(test, a == Axis.ATTR);
break;
}
ip = i;
}
}
if(ax == null) {
ax = Axis.CHILD;
test = nodeTest(false, true);
if(test != null && test.type == NodeType.ATT) ax = Axis.ATTR;
checkTest(test, ax == Axis.ATTR);
}
if(test == null) return null;
final ExprList el = new ExprList();
while(wsConsume(BR1)) {
checkPred(true);
add(el, expr());
wsCheck(BR2);
checkPred(false);
}
return AxisStep.get(info(), ax, test, el.finish());
}
/**
* Parses the "NodeTest" rule.
* Parses the "NameTest" rule.
* Parses the "KindTest" rule.
* @param att attribute flag
* @param all check all tests, or only names
* @return query expression
* @throws QueryException query exception
*/
private Test nodeTest(final boolean att, final boolean all) throws QueryException {
final int i = ip;
if(consume('*')) {
// name test: *
if(!consume(':')) return new NameTest(att);
// name test: *:name
return new NameTest(new QNm(ncName(QNAMEINV)), NameTest.Mode.NAME, att);
}
if(ctx.xquery3 && consume(EQNAME)) {
// name test: {...}*
final byte[] uri = bracedURILiteral();
if(consume('*')) {
final QNm nm = new QNm(COLON, uri);
return new NameTest(nm, NameTest.Mode.NS, att);
}
}
final QNm name = eQName(null, SKIPCHECK);
if(name != null) {
final int i2 = ip;
if(all && wsConsumeWs(PAR1)) {
final NodeType type = NodeType.find(name);
if(type != null) return kindTest(type);
} else {
ip = i2;
// name test: prefix:name, name
if(name.hasPrefix() || !consume(':')) {
skipWS();
names.add(new QNmCheck(name, !att));
return new NameTest(name, NameTest.Mode.STD, att);
}
// name test: prefix:*
if(consume('*')) {
final QNm nm = new QNm(concat(name.string(), COLON));
names.add(new QNmCheck(nm, !att));
return new NameTest(nm, NameTest.Mode.NS, att);
}
}
}
ip = i;
return null;
}
/**
* Parses the "FilterExpr" rule.
* Parses the "Predicate" rule.
* @return postfix expression
* @throws QueryException query exception
*/
private Expr postfix() throws QueryException {
Expr e = primary(), old;
do {
old = e;
if(wsConsume(BR1)) {
if(e == null) error(PREDMISSING);
final ExprList el = new ExprList();
do {
add(el, expr());
wsCheck(BR2);
} while(wsConsume(BR1));
e = new Filter(info(), e, el.finish());
} else if(e != null) {
final Expr[] args = argumentList(e);
if(args == null) break;
final Var[] part = new Var[args.length];
final boolean pt = partial(args, part);
e = new DynamicFunc(info(), e, args);
if(pt) e = new PartFunc(info(), e, part);
}
} while(e != old);
return e;
}
/**
* Fills gaps from place-holders with variable references.
* @param args argument array
* @param vars variables array
* @return variables bound
*/
private boolean partial(final Expr[] args, final Var[] vars) {
final InputInfo ii = info();
boolean found = false;
for(int i = 0; i < args.length; i++) {
if(args[i] == null) {
vars[i] = ctx.uniqueVar(ii, null);
args[i] = new VarRef(ii, vars[i]);
found = true;
}
}
return found;
}
/**
* Parses the "PrimaryExpr" rule.
* Parses the "VarRef" rule.
* Parses the "ContextItem" rule.
* Parses the "Literal" rule.
* @return query expression
* @throws QueryException query exception
*/
private Expr primary() throws QueryException {
skipWS();
final char c = curr();
// variables
if(c == '$') return new VarRef(info(), checkVar(varName(), VARUNDEF));
// parentheses
if(c == '(' && next() != '#') return parenthesized();
// direct constructor
if(c == '<') return constructor();
// function item
if(ctx.xquery3) {
final Expr e = functionItem();
if(e != null) return e;
}
// function call
Expr e = functionCall();
if(e != null) return e;
// computed constructors
e = compConstructor();
if(e != null) return e;
// ordered expression
if(wsConsumeWs(ORDERED, BRACE1, INCOMPLETE) ||
wsConsumeWs(UNORDERED, BRACE1, INCOMPLETE)) return enclosed(NOENCLEXPR);
// map literal
if(wsConsumeWs(MAPSTR, BRACE1, INCOMPLETE)) return mapLiteral();
// context item
if(c == '.' && !digit(next())) {
if(next() == '.') return null;
consume('.');
return new Context(info());
}
// literals
return literal();
}
/**
* Parses a literal map.
* @return map literal
* @throws QueryException query exception
*/
private Expr mapLiteral() throws QueryException {
wsCheck(BRACE1);
final ExprList el = new ExprList();
if(!wsConsume(BRACE2)) {
do {
add(el, check(single(), INVMAPKEY));
wsCheck(ASSIGN);
add(el, check(single(), INVMAPVAL));
} while(wsConsume(COMMA));
wsCheck(BRACE2);
}
return new LitMap(info(), el.finish());
}
/**
* Parses the "FunctionItemExpr" rule.
* Parses the "NamedFunctionRef" rule.
* Parses the "LiteralFunctionItem" rule.
* Parses the "InlineFunction" rule.
* @return query expression, or {@code null}
* @throws QueryException query exception
*/
private Expr functionItem() throws QueryException {
skipWS();
final int pos = ip;
// parse annotations
final Ann ann = ctx.xquery3 && curr('%') ? annotations() : null;
// inline function
if(wsConsume(FUNCTION) && wsConsume(PAR1)) {
final int s = ctx.vars.size();
final Var[] args = paramList();
wsCheck(PAR2);
final SeqType type = optAsType();
final Expr body = enclosed(NOFUNBODY);
ctx.vars.size(s);
return new InlineFunc(info(), type, args, body, ann);
}
// annotations not allowed here
if(ann != null) error(NOANN);
// named function reference
ip = pos;
final QNm name = eQName(null, ctx.sc.nsFunc);
if(name != null && consume('
final long card = ((Int) numericLiteral(true)).itr(null);
if(card < 0 || card > Integer.MAX_VALUE) error(FUNCUNKNOWN, name);
return Functions.get(name, card, false, ctx, info());
}
ip = pos;
return null;
}
/**
* Parses the "Literal" rule.
* @return query expression, or {@code null}
* @throws QueryException query exception
*/
private Item literal() throws QueryException {
final char c = curr();
// literals
if(digit(c) || c == '.') return numericLiteral(false);
// strings
if(!quote(c)) return null;
final int i = ip;
final byte[] s = stringLiteral();
final int p2 = ip;
if(consume(':')) {
// check for EQName
if(!consume('=')) {
ip = i;
return null;
}
ip = p2;
}
return Str.get(s);
}
/**
* Parses the "NumericLiteral" rule.
* Parses the "DecimalLiteral" rule.
* Parses the "IntegerLiteral" rule.
* @param itr integer flag
* @return query expression
* @throws QueryException query exception
*/
private Item numericLiteral(final boolean itr) throws QueryException {
tok.reset();
while(digit(curr())) tok.add(consume());
final boolean dec = consume('.');
if(dec) {
// decimal literal
if(itr) error(NUMBERITR);
tok.add('.');
while(digit(curr()))
tok.add(consume());
}
if(XMLToken.isNCStartChar(curr())) return checkDbl();
if(dec) return new Dec(tok.finish());
final long l = toLong(tok.finish());
if(l == Long.MIN_VALUE) error(RANGE, tok);
return Int.get(l);
}
/**
* Parses the "DoubleLiteral" rule. Checks if a number is followed by a
* whitespace.
* @return expression
* @throws QueryException query exception
*/
private Dbl checkDbl() throws QueryException {
if(!consume('e') && !consume('E')) error(NUMBERWS);
tok.add('e');
if(curr('+') || curr('-')) tok.add(consume());
final int s = tok.size();
while(digit(curr()))
tok.add(consume());
if(s == tok.size()) error(NUMBERINC, tok);
if(XMLToken.isNCStartChar(curr())) error(NUMBERWS);
return Dbl.get(tok.finish(), info());
}
/**
* Parses the "StringLiteral" rule.
* @return query expression
* @throws QueryException query exception
*/
private byte[] stringLiteral() throws QueryException {
skipWS();
final char del = curr();
if(!quote(del)) error(NOQUOTE, found());
consume();
tok.reset();
while(true) {
while(!consume(del)) {
if(!more()) error(NOQUOTE, found());
entity(tok);
}
if(!consume(del)) break;
tok.add(del);
}
return tok.finish();
}
/**
* Parses the "BracedURILiteral" rule without the "Q{" prefix.
* @return query expression
* @throws QueryException query exception
*/
private byte[] bracedURILiteral() throws QueryException {
tok.reset();
while(!consume('}')) {
if(!more()) error(WRONGCHAR, BRACE2, found());
entity(tok);
}
return tok.finish();
}
/**
* Parses the "VarName" rule.
* @return query expression
* @throws QueryException query exception
*/
private QNm varName() throws QueryException {
wsCheck(DOLLAR);
skipWS();
return eQName(NOVARNAME, null);
}
/**
* Parses the "ParenthesizedExpr" rule.
* @return query expression
* @throws QueryException query exception
*/
private Expr parenthesized() throws QueryException {
wsCheck(PAR1);
final Expr e = expr();
wsCheck(PAR2);
return e == null ? Empty.SEQ : e;
}
/**
* Parses the "FunctionCall" rule.
* @return query expression
* @throws QueryException query exception
*/
private Expr functionCall() throws QueryException {
final int i = ip;
final QNm name = eQName(null, ctx.sc.nsFunc);
if(name != null && !keyword(name)) {
final Expr[] args = argumentList(name.string());
if(args != null) {
alter = FUNCUNKNOWN;
alterFunc = name;
ap = ip;
final Var[] vars = new Var[args.length];
final boolean part = partial(args, vars);
final TypedFunc f = Functions.get(name, args, false, ctx, info());
if(f != null) {
alter = null;
return part ? new PartFunc(info(), f, vars) : f.fun;
}
}
}
ip = i;
return null;
}
/**
* Parses the "ArgumentList" rule.
* @param name name of the function (item)
* @return array of arguments, place-holders '?' are represented as
* {@code null} entries
* @throws QueryException query exception
*/
private Expr[] argumentList(final Object name) throws QueryException {
if(!wsConsume(PAR1)) return null;
Expr[] args = { };
if(!wsConsume(PAR2)) {
do {
Expr arg = null;
if(!wsConsume(PLHOLDER) && (arg = single()) == null)
error(FUNCMISS, name);
// speeding up array creation
final int a = args.length;
final Expr[] tmp = new Expr[a + 1];
System.arraycopy(args, 0, tmp, 0, a);
tmp[a] = arg;
args = tmp;
} while(wsConsume(COMMA));
if(!wsConsume(PAR2)) error(FUNCMISS, name);
}
return args;
}
/**
* Parses the "Constructor" rule.
* Parses the "DirectConstructor" rule.
* @return query expression
* @throws QueryException query exception
*/
private Expr constructor() throws QueryException {
check('<');
return consume('!') ? dirComment() : consume('?') ? dirPI() : dirElement();
}
/**
* Parses the "DirElemConstructor" rule.
* Parses the "DirAttributeList" rules.
* @return query expression
* @throws QueryException query exception
*/
private Expr dirElement() throws QueryException {
// cache namespace information
final int s = ctx.sc.ns.size();
final byte[] nse = ctx.sc.nsElem;
final int npos = names.size();
final QNm tag = new QNm(qName(TAGNAME));
names.add(new QNmCheck(tag));
consumeWS();
final Atts ns = new Atts();
final ExprList cont = new ExprList();
// parse attributes...
boolean xmlDecl = false; // xml prefix explicitly declared?
while(true) {
final byte[] atn = qName(null);
if(atn.length == 0) break;
final ExprList attv = new ExprList();
consumeWS();
check('=');
consumeWS();
final char delim = consume();
if(!quote(delim)) error(NOQUOTE, found());
final TokenBuilder tb = new TokenBuilder();
boolean simple = true;
do {
while(!consume(delim)) {
final char ch = curr();
if(ch == '{') {
if(next() == '{') {
tb.add(consume());
consume();
} else {
final byte[] text = tb.finish();
if(text.length != 0) {
add(attv, Str.get(text));
} else {
add(attv, enclosed(NOENCLEXPR));
simple = false;
}
tb.reset();
}
} else if(ch == '}') {
consume();
check('}');
tb.add('}');
} else if(ch == '<' || ch == 0) {
error(NOQUOTE, found());
} else if(ch == '\n' || ch == '\t') {
tb.add(' ');
consume();
} else if(ch == '\r') {
if(next() != '\n') tb.add(' ');
consume();
} else {
entity(tb);
}
}
if(!consume(delim)) break;
tb.add(delim);
} while(true);
if(!tb.isEmpty()) add(attv, Str.get(tb.finish()));
// parse namespace declarations
final boolean pr = startsWith(atn, XMLNSC);
if(pr || eq(atn, XMLNS)) {
if(!simple) error(NSCONS);
final byte[] pref = pr ? local(atn) : EMPTY;
final byte[] uri = attv.isEmpty() ? EMPTY :
((Str) attv.get(0)).string();
if(eq(pref, XML) && eq(uri, XMLURI)) {
if(xmlDecl) error(DUPLNSDEF, XML);
xmlDecl = true;
} else {
if(pr) {
if(uri.length == 0) error(NSEMPTYURI);
if(eq(pref, XML, XMLNS)) error(BINDXML, pref);
if(eq(uri, XMLURI)) error(BINDXMLURI, uri, XML);
if(eq(uri, XMLNSURI)) error(BINDXMLURI, uri, XMLNS);
ctx.sc.ns.add(pref, uri);
} else {
ctx.sc.nsElem = uri;
}
if(ns.get(pref) != -1) error(DUPLNSDEF, pref);
ns.add(pref, uri);
}
} else {
final QNm attn = new QNm(atn);
names.add(new QNmCheck(attn, false));
add(cont, new CAttr(info(), false, attn, attv.finish()));
}
if(!consumeWS()) break;
}
if(consume('/')) {
check('>');
} else {
check('>');
while(curr() != '<' || next() != '/') {
final Expr e = dirElemContent(tag.string());
if(e == null) continue;
add(cont, e);
}
ip += 2;
final byte[] close = qName(TAGNAME);
consumeWS();
check('>');
if(!eq(tag.string(), close)) error(TAGWRONG, tag.string(), close);
}
assignURI(npos);
ctx.sc.ns.size(s);
ctx.sc.nsElem = nse;
return new CElem(info(), tag, ns, cont.finish());
}
/**
* Parses the "DirElemContent" rule.
* @param tag opening tag
* @return query expression
* @throws QueryException query exception
*/
private Expr dirElemContent(final byte[] tag) throws QueryException {
final TokenBuilder tb = new TokenBuilder();
boolean strip = true;
do {
final char c = curr();
if(c == '<') {
if(wsConsume(CDATA)) {
tb.add(cDataSection());
strip = false;
} else {
final Str txt = text(tb, strip);
return txt != null ? txt : next() == '/' ? null : constructor();
}
} else if(c == '{') {
if(next() == '{') {
tb.add(consume());
consume();
} else {
final Str txt = text(tb, strip);
return txt != null ? txt : enclosed(NOENCLEXPR);
}
} else if(c == '}') {
consume();
check('}');
tb.add('}');
} else if(c != 0) {
strip &= !entity(tb);
} else {
error(NOCLOSING, tag);
}
} while(true);
}
/**
* Returns a string item.
* @param tb token builder
* @param strip strip flag
* @return text or {@code null}
*/
private Str text(final TokenBuilder tb, final boolean strip) {
final byte[] t = tb.finish();
return t.length == 0 || strip && !ctx.sc.spaces && ws(t) ?
null : Str.get(t);
}
/**
* Parses the "DirCommentConstructor" rule.
* @return query expression
* @throws QueryException query exception
*/
private Expr dirComment() throws QueryException {
check('-');
check('-');
final TokenBuilder tb = new TokenBuilder();
do {
while(not('-'))
tb.add(consume());
consume();
if(consume('-')) {
check('>');
return new CComm(info(), Str.get(tb.finish()));
}
tb.add('-');
} while(true);
}
/**
* Parses the "DirPIConstructor" rule.
* Parses the "DirPIContents" rule.
* @return query expression
* @throws QueryException query exception
*/
private Expr dirPI() throws QueryException {
final byte[] str = ncName(INVALPI);
if(eq(lc(str), XML)) error(PIXML, str);
final boolean space = skipWS();
final TokenBuilder tb = new TokenBuilder();
do {
while(not('?')) {
if(!space) error(PIWRONG);
tb.add(consume());
}
consume();
if(consume('>')) {
return new CPI(info(), Str.get(str), Str.get(tb.finish()));
}
tb.add('?');
} while(true);
}
/**
* Parses the "CDataSection" rule.
* @return CData
* @throws QueryException query exception
*/
private byte[] cDataSection() throws QueryException {
final TokenBuilder tb = new TokenBuilder();
while(true) {
while(not(']')) {
char ch = consume();
if(ch == '\r') {
ch = '\n';
if(curr(ch)) consume();
}
tb.add(ch);
}
consume();
if(curr(']') && next() == '>') {
ip += 2;
return tb.finish();
}
tb.add(']');
}
}
/**
* Parses the "ComputedConstructor" rule.
* @return query expression
* @throws QueryException query exception
*/
private Expr compConstructor() throws QueryException {
final int i = ip;
if(wsConsumeWs(DOCUMENT)) return consume(compDoc(), i);
if(wsConsumeWs(ELEMENT)) return consume(compElement(), i);
if(wsConsumeWs(ATTRIBUTE)) return consume(compAttribute(), i);
if(wsConsumeWs(NSPACE)) return consume(compNamespace(), i);
if(wsConsumeWs(TEXT)) return consume(compText(), i);
if(wsConsumeWs(COMMENT)) return consume(compComment(), i);
if(wsConsumeWs(PI)) return consume(compPI(), i);
return null;
}
/**
* Consumes the specified expression or resets the query position.
* @param expr expression
* @param p query position
* @return expression or {@code null}
*/
private Expr consume(final Expr expr, final int p) {
if(expr == null) ip = p;
return expr;
}
/**
* Parses the "CompDocConstructor" rule.
* @return query expression
* @throws QueryException query exception
*/
private Expr compDoc() throws QueryException {
if(!wsConsume(BRACE1)) return null;
final Expr e = check(expr(), NODOCCONS);
wsCheck(BRACE2);
return new CDoc(info(), e);
}
/**
* Parses the "CompElemConstructor" rule.
* Parses the "ContextExpr" rule.
* @return query expression
* @throws QueryException query exception
*/
private Expr compElement() throws QueryException {
skipWS();
Expr name;
final QNm qn = eQName(null, SKIPCHECK);
if(qn != null) {
name = qn;
names.add(new QNmCheck(qn));
} else {
if(!wsConsume(BRACE1)) return null;
name = check(expr(), NOTAG);
wsCheck(BRACE2);
}
if(!wsConsume(BRACE1)) return null;
final Expr e = expr();
wsCheck(BRACE2);
return new CElem(info(), name, null, e == null ? new Expr[0] : new Expr[] { e });
}
/**
* Parses the "CompAttrConstructor" rule.
* @return query expression
* @throws QueryException query exception
*/
private Expr compAttribute() throws QueryException {
skipWS();
Expr name;
final QNm qn = eQName(null, SKIPCHECK);
if(qn != null) {
name = qn;
names.add(new QNmCheck(qn, false));
} else {
if(!wsConsume(BRACE1)) return null;
name = expr();
wsCheck(BRACE2);
}
if(!wsConsume(BRACE1)) return null;
final Expr e = expr();
wsCheck(BRACE2);
return new CAttr(info(), true, name, e == null ? Empty.SEQ : e);
}
/**
* Parses the "CompNamespaceConstructor" rule.
* @return query expression
* @throws QueryException query exception
*/
private Expr compNamespace() throws QueryException {
if(!ctx.xquery3) return null;
skipWS();
Expr name;
final byte[] str = ncName(null);
if(str.length != 0) {
name = Str.get(str);
} else {
if(!wsConsume(BRACE1)) return null;
name = check(expr(), NSWRONG);
wsCheck(BRACE2);
}
if(!wsConsume(BRACE1)) return null;
final Expr e = expr();
wsCheck(BRACE2);
return new CNSpace(info(), name, e == null ? Empty.SEQ : e);
}
/**
* Parses the "CompTextConstructor" rule.
* @return query expression
* @throws QueryException query exception
*/
private Expr compText() throws QueryException {
if(!wsConsume(BRACE1)) return null;
final Expr e = check(expr(), NOTXTCONS);
wsCheck(BRACE2);
return new CTxt(info(), e);
}
/**
* Parses the "CompCommentConstructor" rule.
* @return query expression
* @throws QueryException query exception
*/
private Expr compComment() throws QueryException {
if(!wsConsume(BRACE1)) return null;
final Expr e = check(expr(), NOCOMCONS);
wsCheck(BRACE2);
return new CComm(info(), e);
}
/**
* Parses the "CompPIConstructor" rule.
* @return query expression
* @throws QueryException query exception
*/
private Expr compPI() throws QueryException {
skipWS();
Expr name;
final byte[] str = ncName(null);
if(str.length != 0) {
name = Str.get(str);
} else {
if(!wsConsume(BRACE1)) return null;
name = check(expr(), PIWRONG);
wsCheck(BRACE2);
}
if(!wsConsume(BRACE1)) return null;
final Expr e = expr();
wsCheck(BRACE2);
return new CPI(info(), name, e == null ? Empty.SEQ : e);
}
/**
* Parses the "SimpleType" rule.
* @return sequence type
* @throws QueryException query exception
*/
private SeqType simpleType() throws QueryException {
skipWS();
final QNm name = eQName(TYPEINVALID, ctx.sc.nsElem);
final Type t = AtomType.find(name, false);
if(t == null) error(TYPEUNKNOWN, name);
if(t == AtomType.AAT || t == AtomType.NOT) error(CASTUNKNOWN, name);
skipWS();
return SeqType.get(t, consume('?') ? Occ.ZERO_ONE : Occ.ONE);
}
/**
* Parses the "SequenceType" rule.
* Parses the "OccurrenceIndicator" rule.
* Parses the "KindTest" rule.
* @return sequence type
* @throws QueryException query exception
*/
private SeqType sequenceType() throws QueryException {
// empty sequence
if(wsConsumeWs(string(AtomType.EMP.string()), PAR1, null)) {
wsCheck(PAR1);
wsCheck(PAR2);
return SeqType.get(AtomType.EMP, Occ.ONE, null);
}
// parse item type and occurrence indicator
final TypeWrapper tw = itemType();
skipWS();
final Occ occ = consume('?') ? Occ.ZERO_ONE : consume('+') ? Occ.ONE_MORE :
consume('*') ? Occ.ZERO_MORE : Occ.ONE;
skipWS();
return SeqType.get(tw.type, occ, tw.test);
}
/**
* Parses the "ItemType" rule.
* Parses the "ParenthesizedItemType" rule.
* @return item type
* @throws QueryException query exception
*/
private TypeWrapper itemType() throws QueryException {
skipWS();
// parenthesized item type
if(consume(PAR1)) {
final TypeWrapper ret = itemType();
wsCheck(PAR2);
return ret;
}
// parse optional annotation and type name
final Ann ann = ctx.xquery3 && curr('%') ? annotations() : null;
final QNm name = eQName(TYPEINVALID, null);
skipWS();
// check if name is followed by parentheses
final boolean func = curr('(');
// item type
Type t = null;
if(func) {
consume(PAR1);
// item type
if(name.eq(AtomType.ITEM.name)) t = AtomType.ITEM;
// node types
if(t == null) t = NodeType.find(name);
// function types
if(t == null) {
t = FuncType.find(name);
// [LW] XQuery, function test: add annotation support
if(t != null) return new TypeWrapper(functionTest(t));
}
// no type found
if(t == null) error(NOTYPE, new TokenBuilder(name.string()));
} else {
// attach default element namespace
if(!name.hasURI()) name.uri(ctx.sc.nsElem);
// atomic types
t = AtomType.find(name, false);
// no type found
if(t == null) error(TYPEUNKNOWN, name);
}
// annotations are not allowed for remaining types
if(ann != null) error(NOANN);
// atomic value, or closing parenthesis
if(!func || wsConsume(PAR2)) return new TypeWrapper(t);
// raise error if type different to node is not finalized by a parenthesis
if(!(t instanceof NodeType)) wsCheck(PAR2);
// return type with an optional kind test for node types
return new TypeWrapper(t, kindTest((NodeType) t));
}
/**
* Parses the "FunctionTest" rule.
* @param t function type
* @return resulting type
* @throws QueryException query exception
*/
private Type functionTest(final Type t) throws QueryException {
// wildcard
if(wsConsume(ASTERISK)) {
wsCheck(PAR2);
return t;
}
// map
if(t.isMap()) {
final Type key = itemType().type;
if(!key.instanceOf(AtomType.AAT)) error(MAPTAAT, key);
wsCheck(COMMA);
final Type tp = MapType.get((AtomType) key, sequenceType());
wsCheck(PAR2);
return tp;
}
// function type
SeqType[] args = { };
if(!wsConsume(PAR2)) {
// function has got arguments
do {
args = Array.add(args, sequenceType());
} while(wsConsume(COMMA));
wsCheck(PAR2);
}
wsCheck(AS);
final SeqType st = sequenceType();
return FuncType.get(st, args);
}
/**
* Parses the "ElementTest" rule without the type name and the opening bracket.
* @param t type
* @return arguments
* @throws QueryException query exception
*/
private Test kindTest(final NodeType t) throws QueryException {
Test tp = null;
switch(t) {
case DOC: tp = documentTest(); break;
case ELM: tp = elementTest(); break;
case ATT: tp = attributeTest(); break;
case PI: tp = piTest(); break;
case SCE: tp = schemaTest(); break;
case SCA: tp = schemaTest(); break;
default: break;
}
wsCheck(PAR2);
return tp == null ? Test.get(t) : tp;
}
/**
* Parses the "DocumentTest" rule without the leading keyword and its brackets.
* @return arguments
* @throws QueryException query exception
*/
private Test documentTest() throws QueryException {
final boolean elem = consume(ELEMENT);
if(!elem && !consume(SCHEMA_ELEMENT)) return null;
wsCheck(PAR1);
final Test t = elem ? elementTest() : schemaTest();
wsCheck(PAR2);
return new DocTest(t != null ? t : Test.ELM);
}
/**
* Parses the "ElementTest" rule without the leading keyword and its brackets.
* @return arguments
* @throws QueryException query exception
*/
private Test elementTest() throws QueryException {
final QNm name = eQName(null, ctx.sc.nsElem);
if(name == null && !consume(ASTERISK)) return null;
Type type = null;
if(wsConsumeWs(COMMA)) {
// parse type name
final QNm tn = eQName(QNAMEINV, ctx.sc.nsElem);
type = AtomType.find(tn, true);
if(type == null) error(TYPEUNDEF, tn);
// parse optional question mark
wsConsume(PLHOLDER);
}
return new ExtTest(NodeType.ELM, name, type, ctx.sc.strip);
}
/**
* Parses the "ElementTest" rule without the leading keyword and its brackets.
* @return arguments
* @throws QueryException query exception
*/
private Test schemaTest() throws QueryException {
final QNm name = eQName(QNAMEINV, ctx.sc.nsElem);
throw error(SCHEMAINV, name);
}
/**
* Parses the "AttributeTest" rule without the leading keyword and its brackets.
* @return arguments
* @throws QueryException query exception
*/
private Test attributeTest() throws QueryException {
final QNm name = eQName(null, null);
if(name == null && !consume(ASTERISK)) return null;
Type type = null;
if(wsConsumeWs(COMMA)) {
// parse type name
final QNm tn = eQName(QNAMEINV, ctx.sc.nsElem);
type = AtomType.find(tn, true);
if(type == null) error(TYPEUNDEF, tn);
}
return new ExtTest(NodeType.ATT, name, type, ctx.sc.strip);
}
/**
* Parses the "PITest" rule without the leading keyword and its brackets.
* @return arguments
* @throws QueryException query exception
*/
private Test piTest() throws QueryException {
final byte[] nm;
tok.reset();
if(quote(curr())) {
nm = trim(stringLiteral());
if(!XMLToken.isNCName(nm)) error(INVNCNAME, nm);
} else if(ncName()) {
nm = tok.finish();
} else {
return null;
}
return new ExtTest(NodeType.PI, new QNm(nm));
}
/**
* Parses the "TryCatch" rules.
* @return query expression
* @throws QueryException query exception
*/
private Expr tryCatch() throws QueryException {
if(!ctx.xquery3 || !wsConsumeWs(TRY)) return null;
final Expr tr = enclosed(NOENCLEXPR);
wsCheck(CATCH);
Catch[] ct = { };
do {
QNm[] codes = { };
do {
skipWS();
final Test test = nodeTest(false, false);
if(test == null) error(NOCATCH);
codes = Array.add(codes, test.name);
} while(wsConsumeWs(PIPE));
final Catch c = new Catch(info(), codes, ctx);
final int s = c.prepare(ctx);
c.expr = enclosed(NOENCLEXPR);
ctx.vars.size(s);
ct = Array.add(ct, c);
} while(wsConsumeWs(CATCH));
return new Try(info(), tr, ct);
}
/**
* Parses the "FTSelection" rules.
* @param prg pragma flag
* @return query expression
* @throws QueryException query exception
*/
private FTExpr ftSelection(final boolean prg) throws QueryException {
FTExpr expr = ftOr(prg);
FTExpr old;
FTExpr first = null;
boolean ordered = false;
do {
old = expr;
if(wsConsumeWs(ORDERED)) {
ordered = true;
old = null;
} else if(wsConsumeWs(WINDOW)) {
expr = new FTWindow(info(), expr, additive(), ftUnit());
} else if(wsConsumeWs(DISTANCE)) {
final Expr[] rng = ftRange(false);
if(rng == null) error(FTRANGE);
expr = new FTDistance(info(), expr, rng, ftUnit());
} else if(wsConsumeWs(AT)) {
final boolean start = wsConsumeWs(START);
final boolean end = !start && wsConsumeWs(END);
if(!start && !end) error(INCOMPLETE);
expr = new FTContent(info(), expr, start, end);
} else if(wsConsumeWs(ENTIRE)) {
wsCheck(CONTENT);
expr = new FTContent(info(), expr, false, false);
} else {
final boolean same = wsConsumeWs(SAME);
final boolean diff = !same && wsConsumeWs(DIFFERENT);
if(same || diff) {
FTUnit unit = null;
if(wsConsumeWs(SENTENCE)) unit = FTUnit.SENTENCE;
else if(wsConsumeWs(PARAGRAPH)) unit = FTUnit.PARAGRAPH;
else error(INCOMPLETE);
expr = new FTScope(info(), expr, unit, same);
}
}
if(first == null && old != null && old != expr) first = expr;
} while(old != expr);
if(ordered) {
if(first == null) return new FTOrder(info(), expr);
first.expr[0] = new FTOrder(info(), first.expr[0]);
}
return expr;
}
/**
* Parses the "FTOr" rule.
* @param prg pragma flag
* @return query expression
* @throws QueryException query exception
*/
private FTExpr ftOr(final boolean prg) throws QueryException {
final FTExpr e = ftAnd(prg);
if(!wsConsumeWs(FTOR)) return e;
FTExpr[] list = { e };
do list = Array.add(list, ftAnd(prg)); while(wsConsumeWs(FTOR));
return new FTOr(info(), list);
}
/**
* Parses the "FTAnd" rule.
* @param prg pragma flag
* @return query expression
* @throws QueryException query exception
*/
private FTExpr ftAnd(final boolean prg) throws QueryException {
final FTExpr e = ftMildNot(prg);
if(!wsConsumeWs(FTAND)) return e;
FTExpr[] list = { e };
do list = Array.add(list, ftMildNot(prg)); while(wsConsumeWs(FTAND));
return new FTAnd(info(), list);
}
/**
* Parses the "FTMildNot" rule.
* @param prg pragma flag
* @return query expression
* @throws QueryException query exception
*/
private FTExpr ftMildNot(final boolean prg) throws QueryException {
final FTExpr e = ftUnaryNot(prg);
if(!wsConsumeWs(NOT)) return e;
FTExpr[] list = { };
do {
wsCheck(IN);
list = Array.add(list, ftUnaryNot(prg));
} while(wsConsumeWs(NOT));
// convert "A not in B not in ..." to "A not in(B or ...)"
return new FTMildNot(info(), e, list.length == 1 ? list[0] : new FTOr(
info(), list));
}
/**
* Parses the "FTUnaryNot" rule.
* @param prg pragma flag
* @return query expression
* @throws QueryException query exception
*/
private FTExpr ftUnaryNot(final boolean prg) throws QueryException {
final boolean not = wsConsumeWs(FTNOT);
final FTExpr e = ftPrimaryWithOptions(prg);
return not ? new FTNot(info(), e) : e;
}
/**
* Parses the "FTPrimaryWithOptions" rule.
* @param prg pragma flag
* @return query expression
* @throws QueryException query exception
*/
private FTExpr ftPrimaryWithOptions(final boolean prg) throws QueryException {
FTExpr expr = ftPrimary(prg);
final FTOpt fto = new FTOpt();
boolean found = false;
while(ftMatchOption(fto)) found = true;
// check if specified language is not available
if(fto.ln == null) fto.ln = Language.def();
if(!Tokenizer.supportFor(fto.ln)) error(FTNOTOK, fto.ln);
if(fto.is(ST) && fto.sd == null && !Stemmer.supportFor(fto.ln))
error(FTNOSTEM, fto.ln);
// consume weight option
if(wsConsumeWs(WEIGHT)) expr = new FTWeight(info(), expr, enclosed(NOENCLEXPR));
// skip options if none were specified...
return found ? new FTOptions(info(), expr, fto) : expr;
}
/**
* Parses the "FTPrimary" rule.
* @param prg pragma flag
* @return query expression
* @throws QueryException query exception
*/
private FTExpr ftPrimary(final boolean prg) throws QueryException {
final Pragma[] pragmas = pragma();
if(pragmas != null) {
wsCheck(BRACE1);
final FTExpr e = ftSelection(true);
wsCheck(BRACE2);
return new FTExtensionSelection(info(), pragmas, e);
}
if(wsConsumeWs(PAR1)) {
final FTExpr e = ftSelection(false);
wsCheck(PAR2);
return e;
}
skipWS();
final Expr e = curr('{') ? enclosed(NOENCLEXPR)
: quote(curr()) ? Str.get(stringLiteral()) : null;
if(e == null) error(prg ? NOPRAGMA : NOENCLEXPR);
// FTAnyAllOption
FTMode mode = FTMode.ANY;
if(wsConsumeWs(ALL)) {
mode = wsConsumeWs(WORDS) ? FTMode.ALL_WORDS : FTMode.ALL;
} else if(wsConsumeWs(ANY)) {
mode = wsConsumeWs(WORD) ? FTMode.ANY_WORD : FTMode.ANY;
} else if(wsConsumeWs(PHRASE)) {
mode = FTMode.PHRASE;
}
// FTTimes
Expr[] occ = null;
if(wsConsumeWs(OCCURS)) {
occ = ftRange(false);
if(occ == null) error(FTRANGE);
wsCheck(TIMES);
}
return new FTWords(info(), e, mode, occ);
}
/**
* Parses the "FTRange" rule.
* @param i accept only integers ("FTLiteralRange")
* @return query expression
* @throws QueryException query exception
*/
private Expr[] ftRange(final boolean i) throws QueryException {
final Expr[] occ = { Int.get(1), Int.get(Long.MAX_VALUE)};
if(wsConsumeWs(EXACTLY)) {
occ[0] = ftAdditive(i);
occ[1] = occ[0];
} else if(wsConsumeWs(AT)) {
if(wsConsumeWs(LEAST)) {
occ[0] = ftAdditive(i);
} else {
wsCheck(MOST);
occ[0] = Int.get(0);
occ[1] = ftAdditive(i);
}
} else if(wsConsumeWs(FROM)) {
occ[0] = ftAdditive(i);
wsCheck(TO);
occ[1] = ftAdditive(i);
} else {
return null;
}
return occ;
}
/**
* Returns an argument of the "FTRange" rule.
* @param i accept only integers
* @return query expression
* @throws QueryException query exception
*/
private Expr ftAdditive(final boolean i) throws QueryException {
if(!i) return additive();
skipWS();
tok.reset();
while(digit(curr()))
tok.add(consume());
if(tok.isEmpty()) error(INTEXP);
return Int.get(toLong(tok.finish()));
}
/**
* Parses the "FTUnit" rule.
* @return query expression
* @throws QueryException query exception
*/
private FTUnit ftUnit() throws QueryException {
if(wsConsumeWs(WORDS)) return FTUnit.WORD;
if(wsConsumeWs(SENTENCES)) return FTUnit.SENTENCE;
if(wsConsumeWs(PARAGRAPHS)) return FTUnit.PARAGRAPH;
error(INCOMPLETE);
return null;
}
/**
* Parses the "FTMatchOption" rule.
* @param opt options instance
* @return false if no options were found
* @throws QueryException query exception
*/
private boolean ftMatchOption(final FTOpt opt) throws QueryException {
if(!wsConsumeWs(USING)) return false;
if(wsConsumeWs(LOWERCASE)) {
if(opt.isSet(LC) || opt.isSet(UC) || opt.isSet(CS)) error(FTDUP, CASE);
opt.set(CS, true);
opt.set(LC, true);
} else if(wsConsumeWs(UPPERCASE)) {
if(opt.isSet(LC) || opt.isSet(UC) || opt.isSet(CS)) error(FTDUP, CASE);
opt.set(CS, true);
opt.set(UC, true);
} else if(wsConsumeWs(CASE)) {
if(opt.isSet(LC) || opt.isSet(UC) || opt.isSet(CS)) error(FTDUP, CASE);
opt.set(CS, wsConsumeWs(SENSITIVE));
if(!opt.is(CS)) wsCheck(INSENSITIVE);
} else if(wsConsumeWs(DIACRITICS)) {
if(opt.isSet(DC)) error(FTDUP, DIACRITICS);
opt.set(DC, wsConsumeWs(SENSITIVE));
if(!opt.is(DC)) wsCheck(INSENSITIVE);
} else if(wsConsumeWs(LANGUAGE)) {
if(opt.ln != null) error(FTDUP, LANGUAGE);
final byte[] lan = stringLiteral();
opt.ln = Language.get(string(lan));
if(opt.ln == null) error(FTNOTOK, lan);
} else if(wsConsumeWs(OPTION)) {
optionDecl();
} else {
final boolean using = !wsConsumeWs(NO);
if(wsConsumeWs(STEMMING)) {
if(opt.isSet(ST)) error(FTDUP, STEMMING);
opt.set(ST, using);
} else if(wsConsumeWs(THESAURUS)) {
if(opt.th != null) error(FTDUP, THESAURUS);
opt.th = new ThesQuery();
if(using) {
final boolean par = wsConsume(PAR1);
if(!wsConsumeWs(DEFAULT)) ftThesaurusID(opt.th);
while(par && wsConsume(COMMA))
ftThesaurusID(opt.th);
if(par) wsCheck(PAR2);
}
} else if(wsConsumeWs(STOP)) {
// add union/except
wsCheck(WORDS);
if(opt.sw != null) error(FTDUP, STOP + ' ' + WORDS);
opt.sw = new StopWords();
if(wsConsumeWs(DEFAULT)) {
if(!using) error(FTSTOP);
} else {
boolean union = false;
boolean except = false;
while(using) {
if(wsConsume(PAR1)) {
do {
final byte[] sl = stringLiteral();
if(except) opt.sw.delete(sl);
else if(!union || !opt.sw.contains(sl)) opt.sw.add(sl);
} while(wsConsume(COMMA));
wsCheck(PAR2);
} else if(wsConsumeWs(AT)) {
final String fn = string(stringLiteral());
// optional: resolve URI reference
final IO fl = ctx.stop != null ? ctx.stop.get(fn) : ctx.sc.io(fn);
if(!opt.sw.read(fl, except)) error(NOSTOPFILE, fl);
} else if(!union && !except) {
error(FTSTOP);
}
union = wsConsumeWs(UNION);
except = !union && wsConsumeWs(EXCEPT);
if(!union && !except) break;
}
}
} else if(wsConsumeWs(WILDCARDS)) {
if(opt.isSet(WC)) error(FTDUP, WILDCARDS);
if(opt.is(FZ)) error(FTFZWC);
opt.set(WC, using);
} else if(wsConsumeWs(FUZZY)) {
// extension to the official extension: "using fuzzy"
if(opt.isSet(FZ)) error(FTDUP, FUZZY);
if(opt.is(WC)) error(FTFZWC);
opt.set(FZ, using);
} else {
error(FTMATCH, consume());
return false;
}
}
return true;
}
/**
* Parses the "FTThesaurusID" rule.
* @param thes link to thesaurus
* @throws QueryException query exception
*/
private void ftThesaurusID(final ThesQuery thes) throws QueryException {
wsCheck(AT);
final String fn = string(stringLiteral());
// optional: resolve URI reference
final IO fl = ctx.thes != null ? ctx.thes.get(fn) : ctx.sc.io(fn);
final byte[] rel = wsConsumeWs(RELATIONSHIP) ? stringLiteral() : EMPTY;
final Expr[] range = ftRange(true);
long min = 0;
long max = Long.MAX_VALUE;
if(range != null) {
wsCheck(LEVELS);
// values will always be integer instances
min = ((Int) range[0]).itr(info());
max = ((Int) range[1]).itr(info());
}
thes.add(new Thesaurus(fl, rel, min, max, ctx.context));
}
/**
* Parses the "InsertExpr" rule.
* @return query expression
* @throws QueryException query exception
*/
private Expr insert() throws QueryException {
final int i = ip;
if(!wsConsumeWs(INSERT) || !wsConsumeWs(NODE) && !wsConsumeWs(NODES)) {
ip = i;
return null;
}
final Expr s = check(single(), INCOMPLETE);
boolean first = false;
boolean last = false;
boolean before = false;
boolean after = false;
if(wsConsumeWs(AS)) {
first = wsConsumeWs(FIRST);
if(!first) {
wsCheck(LAST);
last = true;
}
wsCheck(INTO);
} else if(!wsConsumeWs(INTO)) {
after = wsConsumeWs(AFTER);
before = !after && wsConsumeWs(BEFORE);
if(!after && !before) error(INCOMPLETE);
}
final Expr trg = check(single(), INCOMPLETE);
ctx.updating(true);
return new Insert(info(), s, first, last, before, after, trg);
}
/**
* Parses the "DeleteExpr" rule.
* @return query expression
* @throws QueryException query exception
*/
private Expr deletee() throws QueryException {
final int i = ip;
if(!wsConsumeWs(DELETE) || !wsConsumeWs(NODES) && !wsConsumeWs(NODE)) {
ip = i;
return null;
}
ctx.updating(true);
return new Delete(info(), check(single(), INCOMPLETE));
}
/**
* Parses the "RenameExpr" rule.
* @return query expression
* @throws QueryException query exception
*/
private Expr rename() throws QueryException {
final int i = ip;
if(!wsConsumeWs(RENAME) || !wsConsumeWs(NODE)) {
ip = i;
return null;
}
final Expr trg = check(single(), INCOMPLETE);
wsCheck(AS);
final Expr n = check(single(), INCOMPLETE);
ctx.updating(true);
return new Rename(info(), trg, n);
}
/**
* Parses the "ReplaceExpr" rule.
* @return query expression
* @throws QueryException query exception
*/
private Expr replace() throws QueryException {
final int i = ip;
if(!wsConsumeWs(REPLACE)) return null;
final boolean v = wsConsumeWs(VALUEE);
if(v) {
wsCheck(OF);
wsCheck(NODE);
} else if(!wsConsumeWs(NODE)) {
ip = i;
return null;
}
final Expr t = check(single(), INCOMPLETE);
wsCheck(WITH);
final Expr r = check(single(), INCOMPLETE);
ctx.updating(true);
return new Replace(info(), t, r, v);
}
/**
* Parses the "TransformExpr" rule.
* @return query expression
* @throws QueryException query exception
*/
private Expr transform() throws QueryException {
if(!wsConsumeWs(COPY, DOLLAR, INCOMPLETE)) return null;
final boolean u = ctx.updating();
ctx.updating(false);
final int s = ctx.vars.size();
Let[] fl = { };
do {
final Var v = Var.create(ctx, info(), varName(), null);
wsCheck(ASSIGN);
final Expr e = check(single(), INCOMPLETE);
ctx.vars.add(v);
fl = Array.add(fl, new Let(info(), e, v));
} while(wsConsumeWs(COMMA));
wsCheck(MODIFY);
final Expr m = check(single(), INCOMPLETE);
wsCheck(RETURN);
final Expr r = check(single(), INCOMPLETE);
ctx.vars.size(s);
ctx.updating(u);
return new Transform(info(), fl, m, r);
}
/**
* Parses the "NCName" rule.
* @param err optional error message
* @return string
* @throws QueryException query exception
*/
private byte[] ncName(final Err err) throws QueryException {
tok.reset();
if(ncName()) return tok.finish();
if(err != null) error(err, tok);
return EMPTY;
}
/**
* Parses the "EQName" rule.
* @param err optional error message. Will be thrown if no EQName is found,
* or ignored if set to {@code null}
* @param def default namespace, or operation mode
* ({@link #URICHECK}, {@link #SKIPCHECK})
* @return string
* @throws QueryException query exception
*/
private QNm eQName(final Err err, final byte[] def) throws QueryException {
final int i = ip;
if(ctx.xquery3 && consume(EQNAME)) {
final byte[] uri = bracedURILiteral();
final byte[] name = ncName(null);
if(name.length != 0) {
if(def == URICHECK && uri.length == 0) error(NOURI, name);
return new QNm(name, uri);
}
ip = i;
}
final byte[] nm = qName(err);
if(nm.length == 0) return null;
if(def == SKIPCHECK) return new QNm(nm);
// create new EQName and set namespace
final QNm name = new QNm(nm, ctx);
if(!name.hasURI()) {
if(def == URICHECK) error(NSMISS, name);
if(name.hasPrefix()) error(NOURI, name);
name.uri(def);
}
return name;
}
/**
* Parses the "QName" rule.
* @param err optional error message. Will be thrown if no QName is found, and
* ignored if set to {@code null}
* @return string
* @throws QueryException query exception
*/
private byte[] qName(final Err err) throws QueryException {
tok.reset();
if(!ncName()) {
if(err != null) error(err, consume());
} else if(consume(':')) {
if(!XMLToken.isNCStartChar(curr())) {
--ip;
} else {
tok.add(':');
do {
tok.add(consume());
} while(XMLToken.isNCChar(curr()));
}
}
return tok.finish();
}
/**
* Helper method for parsing NCNames.
* @return true for success
*/
private boolean ncName() {
if(!XMLToken.isNCStartChar(curr())) return false;
do {
tok.add(consume());
} while(XMLToken.isNCChar(curr()));
return true;
}
/**
* Parses and converts entities.
* @param tb token builder
* @return true if an entity was found
* @throws QueryException query exception
*/
private boolean entity(final TokenBuilder tb) throws QueryException {
final int i = ip;
final boolean ent = consume('&');
if(ent) {
if(consume('
final int b = consume('x') ? 16 : 10;
int n = 0;
do {
final char c = curr();
final boolean m = digit(c);
final boolean h = b == 16
&& (c >= 'a' && c <= 'f' || c >= 'A' && c <= 'F');
if(!m && !h) entityError(i, INVENTITY);
final long nn = n;
n = n * b + (consume() & 15);
if(n < nn) entityError(i, INVCHARREF);
if(!m) n += 9;
} while(!consume(';'));
if(!XMLToken.valid(n)) entityError(i, INVCHARREF);
tb.add(n);
} else {
if(consume("lt")) {
tb.add('<');
} else if(consume("gt")) {
tb.add('>');
} else if(consume("amp")) {
tb.add('&');
} else if(consume("quot")) {
tb.add('"');
} else if(consume("apos")) {
tb.add('\'');
} else {
entityError(i, INVENTITY);
}
if(!consume(';')) entityError(i, INVENTITY);
}
} else {
final char c = consume();
int ch = c;
if(Character.isHighSurrogate(c) && curr() != 0
&& Character.isLowSurrogate(curr())) {
ch = Character.toCodePoint(c, consume());
}
if(ch == '\r') {
ch = '\n';
if(curr(ch)) consume();
}
tb.add(ch);
}
return ent;
}
/**
* Raises an entity error.
* @param p start position
* @param c error code
* @throws QueryException query exception
*/
private void entityError(final int p, final Err c) throws QueryException {
final String sub = input.substring(p, Math.min(p + 20, il));
final int sc = sub.indexOf(';');
final String ent = sc != -1 ? sub.substring(0, sc + 1) : sub;
error(c, ent);
}
/**
* Raises an error if the specified expression is empty.
* @param <E> expression type
* @param expr expression
* @param err error message
* @return expression
* @throws QueryException query exception
*/
private <E extends Expr> E check(final E expr, final Err err) throws QueryException {
if(expr == null) error(err);
return expr;
}
/**
* Raises an error if the specified character cannot be consumed.
* @param ch character to be found
* @throws QueryException query exception
*/
private void check(final int ch) throws QueryException {
if(!consume(ch)) error(WRONGCHAR, (char) ch, found());
}
/**
* Skips whitespaces, raises an error if the specified string cannot be
* consumed.
* @param s string to be found
* @throws QueryException query exception
*/
private void wsCheck(final String s) throws QueryException {
if(!wsConsume(s)) error(WRONGCHAR, s, found());
}
/**
* Checks if a referenced variable is defined and throws the specified error
* if not.
* @param name variable name
* @param err error to throw
* @return referenced variable
* @throws QueryException if the variable isn't defined
*/
private Var checkVar(final QNm name, final Err err) throws QueryException {
Var v = ctx.vars.get(name);
// dynamically assign variables from function modules
if(v == null && !declVars) {
declVars = true;
Variable.init(ctx);
v = ctx.vars.get(name);
}
if(v == null) error(err, '$' + string(name.string()));
return v;
}
/**
* Checks if the specified character is not found. An error is raised if the
* input is exhausted.
* @param ch character to be found
* @return result of check
* @throws QueryException query exception
*/
private boolean not(final char ch) throws QueryException {
final char c = curr();
if(c == 0) error(WRONGCHAR, ch, found());
return c != ch;
}
/**
* Consumes the specified token and surrounding whitespaces.
* @param t token to consume
* @return true if token was found
* @throws QueryException query exception
*/
private boolean wsConsumeWs(final String t) throws QueryException {
final int i = ip;
if(!wsConsume(t)) return false;
if(skipWS() || !XMLToken.isNCStartChar(t.charAt(0))
|| !XMLToken.isNCChar(curr())) return true;
ip = i;
return false;
}
/**
* Consumes the specified two strings or jumps back to the old query position.
* If the strings are found, the cursor is placed after the first token.
* @param s1 string to be consumed
* @param s2 second string
* @param expr alternative error message
* @return result of check
* @throws QueryException query exception
*/
private boolean wsConsumeWs(final String s1, final String s2, final Err expr)
throws QueryException {
final int i = ip;
if(!wsConsumeWs(s1)) return false;
alter = expr;
ap = ip;
final int i2 = ip;
final boolean ok = wsConsume(s2);
ip = ok ? i2 : i;
return ok;
}
/**
* Skips whitespaces, consumes the specified string and ignores trailing
* characters.
* @param str string to consume
* @return true if string was found
* @throws QueryException query exception
*/
private boolean wsConsume(final String str) throws QueryException {
skipWS();
return consume(str);
}
/**
* Consumes all whitespace characters from the remaining query.
* @return true if whitespaces were found
* @throws QueryException query exception
*/
private boolean skipWS() throws QueryException {
final int i = ip;
while(more()) {
final int c = curr();
if(c == '(' && next() == ':') {
comment();
} else {
if(c <= 0 || c > ' ') return i != ip;
++ip;
}
}
return i != ip;
}
/**
* Consumes a comment.
* @throws QueryException query exception
*/
private void comment() throws QueryException {
++ip;
while(++ip < il) {
if(curr('(') && next() == ':') comment();
if(curr(':') && next() == ')') {
ip += 2;
return;
}
}
error(COMCLOSE);
}
/**
* Consumes all following whitespace characters.
* @return true if whitespaces were found
*/
private boolean consumeWS() {
final int i = ip;
while(more()) {
final int c = curr();
if(c <= 0 || c > ' ') return i != ip;
++ip;
}
return true;
}
/**
* Throws the alternative error message.
* @throws QueryException query exception
*/
private void error() throws QueryException {
ip = ap;
if(alter != FUNCUNKNOWN) throw error(alter);
ctx.funcs.funError(alterFunc, info());
throw error(alter, alterFunc.string());
}
/**
* Adds an expression to the specified array.
* @param ar input array
* @param e new expression
* @throws QueryException query exception
*/
private void add(final ExprList ar, final Expr e) throws QueryException {
if(e == null) error(INCOMPLETE);
ar.add(e);
}
/**
* Throws the specified error.
* @param err error to be thrown
* @param arg error arguments
* @return never
* @throws QueryException query exception
*/
public QueryException error(final Err err, final Object... arg) throws QueryException {
throw err.thrw(info(), arg);
}
/**
* Finalizes the QNames by assigning namespace URIs.
* @param npos first entry to be checked
* @throws QueryException query exception
*/
private void assignURI(final int npos) throws QueryException {
for(int i = npos; i < names.size(); i++) {
if(names.get(i).assign(npos == 0)) names.remove(i
}
}
/** Type wrapper. */
private static class TypeWrapper {
/** Type. */
final Type type;
/** Kind test. */
final Test test;
/**
* Constructor.
* @param t type
*/
TypeWrapper(final Type t) {
this(t, null);
}
/**
* Constructor.
* @param t type
* @param k kind test
*/
TypeWrapper(final Type t, final Test k) {
type = t;
test = k;
}
}
/** Cache for checking QNames after their construction. */
private class QNmCheck {
/** QName to be checked. */
final QNm name;
/** Flag for assigning default element namespace. */
final boolean nsElem;
/**
* Constructor.
* @param nm qname
*/
QNmCheck(final QNm nm) {
this(nm, true);
}
/**
* Constructor.
* @param nm qname
* @param nse default check
*/
QNmCheck(final QNm nm, final boolean nse) {
name = nm;
nsElem = nse;
}
/**
* Assigns the namespace URI that is currently in scope.
* @param check check if prefix URI was assigned
* @return true if URI has a URI
* @throws QueryException query exception
*/
boolean assign(final boolean check) throws QueryException {
if(name.hasURI()) return true;
if(name.hasPrefix()) {
name.uri(ctx.sc.ns.uri(name.prefix()));
if(check && !name.hasURI()) error(NOURI, name);
} else if(nsElem) {
name.uri(ctx.sc.nsElem);
}
return name.hasURI();
}
}
}
|
package org.hcjf.utils;
import org.hcjf.properties.SystemProperties;
import javax.crypto.*;
import javax.crypto.spec.GCMParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.spec.AlgorithmParameterSpec;
/**
* @author Andres Medina
*/
public class Cryptography {
private AlgorithmParameterSpec spec;
private Cipher cipher;
private byte[] iv;
private byte[] aadData;
private SecureRandom secureRandom;
private String operationMode;
private final static String TR_PATTERN = "%s/%s/%s";
private SecretKey secretKey;
private int tagBigLength;
public Cryptography() {
this(SystemProperties.get(SystemProperties.Cryptography.KEY),
SystemProperties.getInteger(SystemProperties.Cryptography.Random.IV_SIZE),
SystemProperties.get(SystemProperties.Cryptography.AAD),
SystemProperties.get(SystemProperties.Cryptography.ALGORITHM),
SystemProperties.get(SystemProperties.Cryptography.OPERATION_MODE),
SystemProperties.get(SystemProperties.Cryptography.PADDING_SCHEME),
SystemProperties.getInteger(SystemProperties.Cryptography.GCM.TAG_BIT_LENGTH));
}
public Cryptography(String key, int ivSize,String aad, String algorithm, String operationMode, String paddingScheme, int tagBigLength) {
iv = new byte[ivSize];
aadData = aad.getBytes();
secureRandom = new SecureRandom();
this.tagBigLength = tagBigLength;
this.secretKey = new SecretKeySpec(Strings.hexToBytes(key), "AES");
String transformation = String.format(TR_PATTERN,algorithm,operationMode,paddingScheme);
this.operationMode = operationMode;
try {
cipher = Cipher.getInstance(transformation);
} catch(NoSuchAlgorithmException noSuchAlgoExc) {
System.out.println("Exception while encrypting. Algorithm being requested is not available in this environment " + noSuchAlgoExc);
} catch(NoSuchPaddingException noSuchPaddingExc) {
System.out.println("Exception while encrypting. Padding Scheme being requested is not available this environment " + noSuchPaddingExc);
}
}
public byte[] encrypt(byte[] message) {
secureRandom.nextBytes(iv);
initParameterSpec();
byte[] encryptedMessage = this.convert(Cipher.ENCRYPT_MODE, message);
byte[] result = new byte[encryptedMessage.length + iv.length];
System.arraycopy(iv,0,result,0,iv.length);
System.arraycopy(encryptedMessage,0,result,iv.length,encryptedMessage.length);
return result;
}
public byte[] decrypt(byte[] message) {
byte[] messageFragment = new byte[message.length - iv.length];
System.arraycopy(message,0,iv,0,iv.length);
System.arraycopy(message,iv.length,messageFragment,0,messageFragment.length);
initParameterSpec();
return this.convert(Cipher.DECRYPT_MODE, messageFragment);
}
private void initParameterSpec() {
if(operationMode.equals("GCM")) {
this.spec = new GCMParameterSpec(tagBigLength, iv);
}
}
private byte[] convert(int encryptMode, byte[] message) {
byte[] result = null;
try {
cipher.init(encryptMode, secretKey, spec, new SecureRandom());
} catch(InvalidKeyException invalidKeyExc) {
System.out.println("Exception while encrypting. Key being used is not valid. It could be due to invalid encoding, wrong length or uninitialized " + invalidKeyExc);
} catch(InvalidAlgorithmParameterException invalidAlgoParamExc) {
System.out.println("Exception while encrypting. Algorithm parameters being specified are not valid " + invalidAlgoParamExc);
}
try {
cipher.updateAAD(aadData); // add AAD tag data before encrypting
} catch(IllegalArgumentException illegalArgumentExc) {
System.out.println("Exception thrown while encrypting. Byte array might be null " + illegalArgumentExc );
} catch(IllegalStateException illegalStateExc) {
System.out.println("Exception thrown while encrypting. CIpher is in an illegal state " + illegalStateExc);
} catch(UnsupportedOperationException unsupportedExc) {
System.out.println("Exception thrown while encrypting. Provider might not be supporting this method " + unsupportedExc);
}
try {
result = cipher.doFinal(message) ;
} catch(IllegalBlockSizeException illegalBlockSizeExc) {
System.out.println("Exception while encrypting, due to block size " + illegalBlockSizeExc) ;
} catch(BadPaddingException badPaddingExc) {
System.out.println("Exception while encrypting, due to padding scheme " + badPaddingExc) ;
}
return result;
}
public void setKey(byte[] key) {
this.secretKey = new SecretKeySpec(key, "AES");
}
}
|
package org.jboss.jandex;
import java.io.*;
import java.util.Enumeration;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
/**
*
* Class which contains utility methods to create an index for a jar file
*
* @author Stuart Douglas
*
*/
public class JarIndexer {
/**
* Indexes a jar file and saves the result. If the modify flag is try it is saved META-INF/jandex.idx.
* Otherwies an external file is created with a similar name to the original file, however the
* <code>.jar</code> extension is replaced with <code>-jar.idx</code>
*
* @param jarFile The file to index
* @param indexer The indexer to use
* @param modify If the original jar should be modified
* @param verbose If we should print what we are doing to standard out
*/
public static Result createJarIndex(File jarFile, Indexer indexer, boolean modify, boolean newJar, boolean verbose) throws IOException {
File tmpCopy = null;
ZipOutputStream zo = null;
OutputStream out = null;
File outputFile = null;
JarFile jar = new JarFile(jarFile);
if (modify) {
tmpCopy = File.createTempFile(jarFile.getName().substring(0, jarFile.getName().lastIndexOf('.')), "jmp");
out = zo = new ZipOutputStream(new FileOutputStream(tmpCopy));
} else if (newJar) {
outputFile = new File(jarFile.getAbsolutePath().replace(".jar", "-jandex.jar"));
out = zo = new ZipOutputStream(new FileOutputStream(outputFile));
} else
{
outputFile = new File(jarFile.getAbsolutePath().replace(".jar", "-jar") + ".idx");
out = new FileOutputStream( outputFile);
}
try {
Enumeration<JarEntry> entries = jar.entries();
while (entries.hasMoreElements()) {
JarEntry entry = entries.nextElement();
if (modify) {
zo.putNextEntry(entry);
copy(jar.getInputStream(entry), zo);
}
if (entry.getName().endsWith(".class")) {
ClassInfo info = indexer.index(jar.getInputStream(entry));
if (verbose && info != null)
printIndexEntryInfo(info);
}
}
if (modify || newJar) {
zo.putNextEntry(new ZipEntry("META-INF/jandex.idx"));
}
IndexWriter writer = new IndexWriter(out);
Index index = indexer.complete();
int bytes = writer.write(index);
out.close();
zo.close();
jar.close();
if (modify) {
jarFile.delete();
tmpCopy.renameTo(jarFile);
tmpCopy = null;
}
return new Result(index, modify ? "META-INF/jandex.idx" : outputFile.getPath(), bytes);
} finally {
out.flush();
out.close();
if (tmpCopy != null)
tmpCopy.delete();
}
}
private static void printIndexEntryInfo(ClassInfo info) {
System.out.println("Indexed " + info.name() + " (" + info.annotations().size() + " annotations)");
}
private static void copy(InputStream in, OutputStream out) throws IOException {
byte[] buf = new byte[8192];
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
out.flush();
}
private JarIndexer() {
}
}
|
package org.jtrfp.trcl.core;
import java.awt.Color;
import java.awt.image.BufferedImage;
import java.io.InputStream;
import java.nio.ByteBuffer;
import java.nio.IntBuffer;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.concurrent.Callable;
import javax.imageio.ImageIO;
import javax.media.opengl.GL3;
import org.apache.commons.math3.geometry.euclidean.threed.Vector3D;
import org.jtrfp.trcl.SpecialRAWDimensions;
import org.jtrfp.trcl.TextureBehavior;
import org.jtrfp.trcl.Triangle;
import org.jtrfp.trcl.TriangleList;
import org.jtrfp.trcl.core.VQCodebookManager.RasterRowWriter;
import org.jtrfp.trcl.gpu.GPU;
import org.jtrfp.trcl.img.vq.BufferedImageRGBA8888VL;
import org.jtrfp.trcl.img.vq.ByteBufferVectorList;
import org.jtrfp.trcl.img.vq.ConstantVectorList;
import org.jtrfp.trcl.img.vq.PalettedVectorList;
import org.jtrfp.trcl.img.vq.RGBA8888VectorList;
import org.jtrfp.trcl.img.vq.RasterizedBlockVectorList;
import org.jtrfp.trcl.img.vq.SubtextureVL;
import org.jtrfp.trcl.img.vq.VectorList;
import org.jtrfp.trcl.img.vq.VectorListND;
import org.jtrfp.trcl.img.vq.VectorListRasterizer;
import org.jtrfp.trcl.math.Misc;
import org.jtrfp.trcl.mem.PagedByteBuffer;
import org.jtrfp.trcl.mem.VEC4Address;
import org.jtrfp.trcl.pool.IntArrayList;
public class Texture implements TextureDescription {
private final ThreadManager threadManager;
private final TextureManager tm ;
private final VQCodebookManager cbm;
private final TextureTOCWindow toc;
private final SubTextureWindow stw;
private Color averageColor;
private final String debugName;
private Integer tocIndex;
private int[] subTextureIDs;
private int[][] codebookStartOffsetsAbsolute;
private final boolean uvWrapping;
private volatile int texturePage;
private int sideLength;
private TextureBehavior.Support tbs = new TextureBehavior.Support();
@Override
public void finalize() throws Throwable{
//TOC ID
if(tocIndex!=null)
toc.free(tocIndex);
//Subtexture IDs
if(subTextureIDs!=null)
for(int stID:subTextureIDs)
stw.free(stID);
//Codebook entries
if(codebookStartOffsetsAbsolute!=null)
for(int [] array:codebookStartOffsetsAbsolute){
//for(int entry:array){
// tm.vqCodebookManager.get().freeCodebook256(entry/256);
for(int i=0; i<array.length;i++)
array[i]/=256;//WARNING: This corrupts the original data
tm.vqCodebookManager.get().freeCodebook256(new IntArrayList(array).setRepresentFullSize(true));
// }//end for(entries)
}//end for(arrays)
super.finalize();
}//end finalize()
Texture(GPU gpu, ThreadManager threadManager, Color c){
this(gpu,threadManager,new PalettedVectorList(colorZeroRasterVL(), colorVL(c)),null,"SolidColor r="+c.getRed()+" g="+c.getGreen()+" b="+c.getBlue(),false);
}//end constructor
private static VectorList colorZeroRasterVL(){
return new VectorList(){
@Override
public int getNumVectors() {
return 16;
}
@Override
public int getNumComponentsPerVector() {
return 1;
}
@Override
public double componentAt(int vectorIndex, int componentIndex) {
return 0;
}
@Override
public void setComponentAt(int vectorIndex, int componentIndex,
double value) {
throw new RuntimeException("Cannot write to Texture.colorZeroRasterVL VectorList");
}};
}//end colorZeroRasterVL
private static VectorList colorVL(Color c){
final double [] color = new double[]{
c.getRed()/255.,c.getGreen()/255.,c.getBlue()/255.,c.getAlpha()/255.};
return new VectorList(){
@Override
public int getNumVectors() {
return 1;
}
@Override
public int getNumComponentsPerVector() {
return 4;
}
@Override
public double componentAt(int vectorIndex, int componentIndex) {
return color[componentIndex];
}
@Override
public void setComponentAt(int vectorIndex, int componentIndex,
double value) {
throw new RuntimeException("Static palette created by Texture(Color c, TR tr) cannot be written to.");
}};
}//end colorVL(...)
private Texture(GPU gpu, ThreadManager threadManager, String debugName, boolean uvWrapping){
this.threadManager=threadManager;
this.tm =gpu.textureManager.get();
this.cbm =tm.vqCodebookManager.get();
this.toc =tm.getTOCWindow();
this.stw =tm.getSubTextureWindow();
this.debugName =debugName.replace('.', '_');
this.uvWrapping =uvWrapping;
}//end constructor
Texture(GPU gpu, ThreadManager threadManager, PalettedVectorList vlRGBA, PalettedVectorList vlESTuTv, String debugName, boolean uvWrapping){
this(gpu,threadManager,debugName,uvWrapping);
vqCompress(vlRGBA,vlESTuTv);
}//end constructor
Texture(GPU gpu, ThreadManager threadManager, ByteBuffer imageRGBA8888, ByteBuffer imageESTuTv8888, String debugName, boolean uvWrapping) {
this(gpu,threadManager,debugName,uvWrapping);
if (imageRGBA8888.capacity() == 0) {
throw new IllegalArgumentException(
"Cannot create texture of zero size.");
}//end if capacity==0
imageRGBA8888.clear();//Doesn't erase, just resets the tracking vars
vqCompress(imageRGBA8888,imageESTuTv8888);
}// end constructor
private void vqCompress(PalettedVectorList squareImageIndexedRGBA,PalettedVectorList squareImageIndexedESTuTv){
final double fuzzySideLength = Math.sqrt(squareImageIndexedRGBA.getNumVectors());
final int sideLength = (int)Math.floor(fuzzySideLength);
if(!SpecialRAWDimensions.isPowerOfTwo(sideLength))
System.err.println("WARNING: Calculated dimensions are not power-of-two. Trouble ahead.");
if(Math.abs(fuzzySideLength-sideLength)>.001)
System.err.println("WARNING: Calculated dimensions are not perfectly square. Trouble ahead.");
vqCompress(squareImageIndexedRGBA, squareImageIndexedESTuTv,sideLength);
}
private void vqCompress(ByteBuffer imageRGBA8888, ByteBuffer imageESTuTv8888){
final double fuzzySideLength = Math.sqrt((imageRGBA8888.capacity() / 4));
final int sideLength = (int)Math.floor(fuzzySideLength);
if(!SpecialRAWDimensions.isPowerOfTwo(sideLength))
System.err.println("WARNING: Calculated dimensions are not power-of-two. Trouble ahead.");
if(Math.abs(fuzzySideLength-sideLength)>.001)
System.err.println("WARNING: Calculated dimensions are not perfectly square. Trouble ahead.");
// Break down into 4x4 blocks
final ByteBufferVectorList bbvl = new ByteBufferVectorList(imageRGBA8888);
final RGBA8888VectorList rgba8888vl = new RGBA8888VectorList(bbvl);
final VectorList bbvlESTuTv = imageESTuTv8888!=null?new ByteBufferVectorList(imageESTuTv8888):new ConstantVectorList(0,bbvl);
final RGBA8888VectorList esTuTv8888vl = bbvlESTuTv!=null?new RGBA8888VectorList(bbvlESTuTv):null;
vqCompress(rgba8888vl,esTuTv8888vl,sideLength);
}
private final void vqCompress(VectorList rgba8888vl, VectorList esTuTv8888vl, final int sideLength){
this.sideLength=sideLength;
final int diameterInCodes = (int)Misc.clamp((double)sideLength/(double)VQCodebookManager.CODE_SIDE_LENGTH, 1, Integer.MAX_VALUE);
final int diameterInSubtextures = (int)Math.ceil((double)diameterInCodes/(double)SubTextureWindow.SIDE_LENGTH_CODES_WITH_BORDER);
final RasterizedBlockVectorList rbvlRGBA = new RasterizedBlockVectorList(
new VectorListRasterizer(rgba8888vl,new int[]{sideLength,sideLength}), 4);
final VectorListND vlrRGBA = rbvlRGBA;
final RasterizedBlockVectorList rbvlESTuTv =
esTuTv8888vl!=null?
new RasterizedBlockVectorList(
new VectorListRasterizer(esTuTv8888vl, new int[]{sideLength,sideLength}), 4):null;
final VectorListND vlrESTuTv =
rbvlESTuTv!=null?
rbvlESTuTv:null;
// Calculate a rough average color by averaging random samples.
calulateAverageColor(rbvlRGBA);
// Get a TOC
tocIndex = toc.create();
setTexturePage((toc.getPhysicalAddressInBytes(tocIndex).intValue()/PagedByteBuffer.PAGE_SIZE_BYTES));
if(toc.getPhysicalAddressInBytes(tocIndex).intValue()%PagedByteBuffer.PAGE_SIZE_BYTES!=0)
throw new RuntimeException("Physical GPU address not perfectly aligned with page interval.");
threadManager.submitToThreadPool(new Callable<Void>(){
@Override
public Void call() throws Exception {
// Create subtextures
subTextureIDs = new int[diameterInSubtextures*diameterInSubtextures];
codebookStartOffsetsAbsolute = new int[diameterInSubtextures*diameterInSubtextures][6];
for(int i=0; i<subTextureIDs.length; i++){
//Create subtexture ID
subTextureIDs[i]=stw.create();
tm.vqCodebookManager.get().newCodebook256(new IntArrayList(codebookStartOffsetsAbsolute[i]), 6);
for(int off=0; off<6; off++){
codebookStartOffsetsAbsolute[i][off]*= 256;}
}//end for(subTextureIDs)
threadManager.submitToGPUMemAccess(new Callable<Void>() {
@Override
public final Void call() {
//Set magic
toc.magic.set(tocIndex, 1337);
for(int i=0; i<subTextureIDs.length; i++){
final int id = subTextureIDs[i];
//Convert subtexture index to index of TOC
final int tocSubTexIndex = (i%diameterInSubtextures)+(i/diameterInSubtextures)*TextureTOCWindow.WIDTH_IN_SUBTEXTURES;
//Load subtexture ID into TOC
toc.subtextureAddrsVec4.setAt(tocIndex, tocSubTexIndex,new VEC4Address(stw.getPhysicalAddressInBytes(id)).intValue());
//Render Flags
toc.renderFlags.set(tocIndex,
(uvWrapping?0x1:0x0)
);
//Fill the subtexture code start offsets
for(int off=0; off<6; off++)
stw.codeStartOffsetTable.setAt(id, off, codebookStartOffsetsAbsolute[i][off]);
}//end for(subTextureIDs)
// Set the TOC vars
toc.height .set(tocIndex, sideLength);
toc.width .set(tocIndex, sideLength);
setCodes(diameterInCodes, diameterInSubtextures);
return null;
}// end run()
//REQUIRES GPU MEM ACCESS
private final void setCodes(int diameterInCodes, int diameterInSubtextures){
final int numCodes = diameterInCodes*diameterInCodes;
for(int i = 0; i < numCodes; i++){
final int codeX = i % diameterInCodes;
final int codeY = i / diameterInCodes;
setCodeAt(codeX,codeY);
}//end for(numCodes)
}//end setCodes()
//REQUIRES GPU MEM ACCESS
private final void setCodeAt(int codeX, int codeY){
final int subtextureX = codeX / SubTextureWindow.SIDE_LENGTH_CODES_WITH_BORDER;
final int subtextureY = codeY / SubTextureWindow.SIDE_LENGTH_CODES_WITH_BORDER;
final int subtextureCodeX = codeX % SubTextureWindow.SIDE_LENGTH_CODES_WITH_BORDER;
final int subtextureCodeY = codeY % SubTextureWindow.SIDE_LENGTH_CODES_WITH_BORDER;
final int codeIdx = subtextureCodeX + subtextureCodeY * SubTextureWindow.SIDE_LENGTH_CODES_WITH_BORDER;
final int subTextureIdx = subtextureX + subtextureY * diameterInSubtextures;
final int subtextureID = subTextureIDs[subTextureIdx];
new SubtextureVL(stw, subtextureID).setComponentAt(codeIdx, 0, (byte)(codeIdx%256));//TODO: Could make a lot of garbage.
}//end setCodeAt()
}).get();//end gpuMemThread
// Push texels to codebook
for(int codeY=0; codeY<diameterInCodes; codeY++){
for(int codeX=0; codeX<diameterInCodes; codeX++){
final int subtextureX = codeX / SubTextureWindow.SIDE_LENGTH_CODES_WITH_BORDER;
final int subtextureY = codeY / SubTextureWindow.SIDE_LENGTH_CODES_WITH_BORDER;
final int subTextureIdx = subtextureX + subtextureY * diameterInSubtextures;
final int subtextureCodeX = codeX % SubTextureWindow.SIDE_LENGTH_CODES_WITH_BORDER;
final int subtextureCodeY = codeY % SubTextureWindow.SIDE_LENGTH_CODES_WITH_BORDER;
final int codeIdx = subtextureCodeX + subtextureCodeY * SubTextureWindow.SIDE_LENGTH_CODES_WITH_BORDER;
final int globalCodeIndex = codeIdx%256
+ codebookStartOffsetsAbsolute[subTextureIdx][codeIdx/256];
setRGBACodebookTexelsAt(vlrRGBA, codeX,codeY,diameterInCodes, globalCodeIndex);
if(vlrESTuTv!=null)
setESTuTvCodebookTexelsAt(vlrESTuTv, codeX,codeY,diameterInCodes, globalCodeIndex);
}//end for(codeX)
}//end for(codeY)
flushRGBACodeblock256();
flushESTuTvCodeblock256();
return null;
}//end threadPool call()
private void setRGBACodebookTexelsAt(final VectorListND vlrRGBA, int codeX, int codeY,
int diameterInCodes, int globalCodeIndex) {
final int coord[] = new int[]{codeX,codeY};
final RasterRowWriter rw = new RowWriterImpl(vlrRGBA,coord);
try {
registerRGBAToBlock256(globalCodeIndex, rw);
} catch (ArrayIndexOutOfBoundsException e) {
throw new RuntimeException("this="
+ Texture.this.toString(), e);
}//end catch(ArrayIndexOutOfBoundsException)
}// end setCodebookTexelsAt
private void setESTuTvCodebookTexelsAt(final VectorListND vlrESTuTv, int codeX, int codeY,
int diameterInCodes, int globalCodeIndex) {
final int coord[] = new int[]{codeX,codeY};
final RasterRowWriter rw = new RowWriterImpl(vlrESTuTv,coord);
try {
registerESTuTvToBlock256(globalCodeIndex, rw);
} catch (ArrayIndexOutOfBoundsException e) {
throw new RuntimeException("this="
+ Texture.this.toString(), e);
}//end catch(ArrayIndexOutOfBoundsException)
}// end setCodebookTexelsAt
final class RowWriterImpl implements RasterRowWriter{
private final VectorListND _vlr;
private final int [] coord;
public RowWriterImpl(VectorListND vlrRGBA, int [] coord){
this._vlr=vlrRGBA;
this.coord=coord;
}
@Override
public void applyRow(int row, ByteBuffer dest) {
int position = row * 16;
dest.put((byte) (_vlr
.componentAt(coord, position++) * 255.));
dest.put((byte) (_vlr
.componentAt(coord, position++) * 255.));
dest.put((byte) (_vlr
.componentAt(coord, position++) * 255.));
dest.put((byte) (_vlr
.componentAt(coord, position++) * 255.));
dest.put((byte) (_vlr
.componentAt(coord, position++) * 255.));
dest.put((byte) (_vlr
.componentAt(coord, position++) * 255.));
dest.put((byte) (_vlr
.componentAt(coord, position++) * 255.));
dest.put((byte) (_vlr
.componentAt(coord, position++) * 255.));
dest.put((byte) (_vlr
.componentAt(coord, position++) * 255.));
dest.put((byte) (_vlr
.componentAt(coord, position++) * 255.));
dest.put((byte) (_vlr
.componentAt(coord, position++) * 255.));
dest.put((byte) (_vlr
.componentAt(coord, position++) * 255.));
dest.put((byte) (_vlr
.componentAt(coord, position++) * 255.));
dest.put((byte) (_vlr
.componentAt(coord, position++) * 255.));
dest.put((byte) (_vlr
.componentAt(coord, position++) * 255.));
dest.put((byte) (_vlr
.componentAt(coord, position++) * 255.));
}// end applyRow
}//end RasterRowWriter
private final Map<Integer,RasterRowWriter[]>rgbaBlock256Map = new HashMap<Integer,RasterRowWriter[]>();
private final Map<Integer,RasterRowWriter[]>ESTuTvBlock256Map = new HashMap<Integer,RasterRowWriter[]>();
private final void registerRGBAToBlock256(int globalCodeIndex, RasterRowWriter rw){
RasterRowWriter[] writers = getRGBABlock256(globalCodeIndex);
writers[globalCodeIndex%256]=rw;
}//end registerRGBAToBlock256
private final void registerESTuTvToBlock256(int globalCodeIndex, RasterRowWriter rw){
RasterRowWriter[] writers = getESTuTvBlock256(globalCodeIndex);
writers[globalCodeIndex%256]=rw;
}//end registerRGBAToBlock256
private final RasterRowWriter[] getRGBABlock256(int globalCodeIndex){
final int key = globalCodeIndex/256;
RasterRowWriter [] writers = rgbaBlock256Map.get(key);
if(writers==null)
rgbaBlock256Map.put(key,writers = new RasterRowWriter[256]);
return writers;
}//end getRGBABlock256(...)
private final RasterRowWriter[] getESTuTvBlock256(int globalCodeIndex){
final int key = globalCodeIndex/256;
RasterRowWriter [] writers = ESTuTvBlock256Map.get(key);
if(writers==null)
ESTuTvBlock256Map.put(key,writers = new RasterRowWriter[256]);
return writers;
}//end getESTuTvBlock256(...)
private final void flushRGBACodeblock256(){
for(Entry<Integer,RasterRowWriter[]> entry:rgbaBlock256Map.entrySet()){
cbm.setRGBABlock256(entry.getKey(),entry.getValue());
}//end for(entries)
}//end flushRGBACodeblock256()
private final void flushESTuTvCodeblock256(){
for(Entry<Integer,RasterRowWriter[]> entry:ESTuTvBlock256Map.entrySet()){
cbm.setESTuTvBlock256(entry.getKey(),entry.getValue());
}//end for(entries)
}//end flushRGBACodeblock256()
}).get();// end pool thread
}//end vqCompress(...)
private void calulateAverageColor(RasterizedBlockVectorList rbvl) {
float redA=0,greenA=0,blueA=0;
final double size = rbvl.getNumVectors();
final int [] dims = rbvl.getDimensions();
for(int i=0; i<10; i++){
redA+=rbvl.componentAt(new int[]{(int)(Math.random()*dims[0]),(int)(Math.random()*dims[1])} ,0);
greenA+=rbvl.componentAt(new int[]{(int)(Math.random()*dims[0]),(int)(Math.random()*dims[1])} ,1);
blueA+=rbvl.componentAt(new int[]{(int)(Math.random()*dims[0]),(int)(Math.random()*dims[1])} ,2);
}averageColor = new Color(redA/10f,greenA/10f,blueA/10f);
}//end calculateAverageColor(...)
Texture(GPU gpu, ThreadManager threadManager, BufferedImage imgRGBA, BufferedImage imgESTuTv, String debugName, boolean uvWrapping) {
this(gpu,threadManager,debugName,uvWrapping);
try{
vqCompress(new BufferedImageRGBA8888VL(imgRGBA),
imgESTuTv!=null?
new BufferedImageRGBA8888VL(imgESTuTv):
null,imgRGBA.getWidth());
}catch(Exception e){e.printStackTrace();}
}//end constructor
public static ByteBuffer RGBA8FromPNG(InputStream is) {
try {
BufferedImage bi = ImageIO.read(is);
return RGBA8FromPNG(bi, 0, 0, bi.getWidth(), bi.getHeight());
} catch (Exception e) {
e.printStackTrace();
}
return null;
}//end RGBA8FromPNG(...)
public static ByteBuffer RGBA8FromPNG(BufferedImage image, int startX,
int startY, int sizeX, int sizeY) {
//int color;
ByteBuffer buf = ByteBuffer.allocateDirect(image.getWidth()
* image.getHeight() * 4);
final int [] row = new int[image.getWidth()];
for (int y = startY; y < startY + sizeY; y++) {
image.getRGB(0, y, image.getWidth(), 1, row, 0, image.getWidth());
for (int color:row) {
buf.put((byte) ((color & 0x00FF0000) >> 16));
buf.put((byte) ((color & 0x0000FF00) >> 8));
buf.put((byte) (color & 0x000000FF));
buf.put((byte) ((color & 0xFF000000) >> 24));
}// end for(x)
}// end for(y)
buf.clear();// Rewind
return buf;
}// end RGB8FromPNG(...)
public static final Color[] GREYSCALE;
static {
GREYSCALE = new Color[256];
for (int i = 0; i < 256; i++) {
GREYSCALE[i] = new Color(i, i, i);
}
}// end static{}
public static ByteBuffer fragmentRGBA(ByteBuffer input, int quadDepth,
int x, int y) {
final int originalSideLen = (int) Math.sqrt(input.capacity() / 4);
final int splitAmount = (int) Math.pow(2, quadDepth);
final int newSideLen = originalSideLen / splitAmount;
ByteBuffer result = ByteBuffer.allocateDirect((int) (Math.pow(
newSideLen, 2) * 4));
for (int row = y * newSideLen; row < (y + 1) * newSideLen; row++) {
input.clear();
input.limit((x + 1) * newSideLen * 4 + row * originalSideLen * 4);
input.position(x * newSideLen * 4 + row * originalSideLen * 4);
result.put(input);
}
return result;
}// end fragmentRGBA(...)
public static ByteBuffer indexed2RGBA8888(ByteBuffer indexedPixels,
Color[] palette) {
Color color;
ByteBuffer buf = ByteBuffer.allocateDirect(indexedPixels.capacity() * 4);
final int cap = indexedPixels.capacity();
for (int i = 0; i < cap; i++) {
color = palette[(indexedPixels.get() & 0xFF)];
buf.put((byte) color.getRed());
buf.put((byte) color.getGreen());
buf.put((byte) color.getBlue());
buf.put((byte) color.getAlpha());
}// end for(i)
buf.clear();// Rewind
return buf;
}// end indexed2RGBA8888(...)
public static ByteBuffer[] indexed2RGBA8888(ByteBuffer[] indexedPixels,
Color[] palette) {
final int len = indexedPixels.length;
ByteBuffer[] result = new ByteBuffer[len];
for (int i = 0; i < len; i++) {
result[i] = indexed2RGBA8888(indexedPixels[i], palette);
}
return result;
}// end indexed2RGBA8888(...)
/**
* @return the uvWrapping
*/
public boolean isUvWrapping() {
return uvWrapping;
}
/**
* @return the texturePage
*/
public int getTexturePage() {
return texturePage;
}
/**
* @param texturePage the texturePage to set
*/
public void setTexturePage(int texturePage) {
this.texturePage = texturePage;
}
@Override
public Color getAverageColor() {
return averageColor;
}
public static final int createTextureID(GL3 gl) {
IntBuffer ib = IntBuffer.allocate(1);
gl.glGenTextures(1, ib);
ib.clear();
return ib.get();
}//end createTextureID
@Override
public String toString(){
return "Texture debugName="+debugName+" width="+sideLength;
}
public int getSideLength(){
return sideLength;
}
/**
* @param beh
* @see org.jtrfp.trcl.TextureBehavior.Support#addBehavior(org.jtrfp.trcl.TextureBehavior)
*/
public void addBehavior(TextureBehavior beh) {
tbs.addBehavior(beh);
}
/**
* @param beh
* @see org.jtrfp.trcl.TextureBehavior.Support#removeBehavior(org.jtrfp.trcl.TextureBehavior)
*/
public void removeBehavior(TextureBehavior beh) {
tbs.removeBehavior(beh);
}
/**
* @param triangleList
* @param gpuTVIndex
* @param numFrames
* @param thisTriangle
* @param pos
* @param vw
* @see org.jtrfp.trcl.TextureBehavior.Support#apply(org.jtrfp.trcl.TriangleList, int, int, org.jtrfp.trcl.Triangle, org.apache.commons.math3.geometry.euclidean.threed.Vector3D, org.jtrfp.trcl.core.TriangleVertexWindow)
*/
public void apply(TriangleList triangleList, int gpuTVIndex, int numFrames,
Triangle thisTriangle, Vector3D pos, TriangleVertexWindow vw) {
tbs.apply(triangleList, gpuTVIndex, numFrames, thisTriangle, pos, vw);
}
}// end Texture
|
package org.lantern;
import java.io.IOException;
import java.net.InetAddress;
import java.util.Collection;
import java.util.TreeSet;
import org.apache.commons.lang.StringUtils;
import org.lastbamboo.common.stun.client.PublicIpAddress;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.collect.Sets;
/**
* Class that keeps track of which countries are considered censored.
*/
public class DefaultCensored implements Censored {
private final Logger LOG =
LoggerFactory.getLogger(DefaultCensored.class);
private static final Collection<String> CENSORED =
new TreeSet<String>(Sets.newHashSet(
// These are taken from ONI data -- 11/16 - any country containing
// any type of censorship considered "substantial" or "pervasive".
"AE", // United Arab Emirates
"AM", // Armenia
"BH", // Bahrain
"CN", // China
"CU", // Cuba
"ET", // Ethiopia
"ID", // Indonesia
"IR", // Iran
"KP", // North Korea
"KR", // South Korea
"KW", // Kuwait
"MM", // Myanmar
"OM", // Oman
"PK", // Pakistan
"PS", // Palestine
"QA", // Qatar
"SA", // Saudi Arabia
"SD", // Sudan
"SY", // Syria
"TM", // Turkmenistan
"UZ", // Uzbekistan
"VN", // Vietnam
"YE" // Yemen
));
public DefaultCensored() {
CENSORED.add("CU");
CENSORED.add("KP");
}
// These country codes have US export restrictions, and therefore cannot
// access App Engine sites.
private final Collection<String> EXPORT_RESTRICTED =
Sets.newHashSet(
"SY");
private String countryCode;
@Override
public String countryCode() {
if (StringUtils.isNotBlank(countryCode)) {
LOG.info("Returning cached country code: {}", countryCode);
return countryCode;
}
LOG.info("Returning country code: {}", countryCode);
countryCode = country().getCode().trim();
return countryCode;
}
@Override
public Country country() {
final InetAddress address = new PublicIpAddress().getPublicIpAddress();
if (address == null) {
// Just return an empty country instead of throwing null pointer.
return new Country("", "");
}
final com.maxmind.geoip.Country country =
LanternHub.getGeoIpLookup().getCountry(address);
return new Country(country.getCode(), country.getName());
}
@Override
public boolean isCensored() {
return isCensored(new PublicIpAddress().getPublicIpAddress());
}
@Override
public boolean isCensored(final Country country) {
final String cc = country.getCode().trim();
return CENSORED.contains(cc);
}
@Override
public Collection<String> getCensored() {
return CENSORED;
}
@Override
public boolean isCensored(final String address) throws IOException {
return isCensored(InetAddress.getByName(address));
}
@Override
public boolean isCountryCodeCensored(final String cc) {
if (StringUtils.isBlank(cc)) {
return false;
}
return CENSORED.contains(cc);
}
public boolean isExportRestricted() {
return isExportRestricted(new PublicIpAddress().getPublicIpAddress());
}
public boolean isExportRestricted(final InetAddress address) {
return isMatch(address, EXPORT_RESTRICTED);
}
@Override
public boolean isExportRestricted(final String address)
throws IOException {
return isExportRestricted(InetAddress.getByName(address));
}
private boolean isCensored(final InetAddress address) {
return isMatch(address, CENSORED);
}
private boolean isMatch(final InetAddress address,
final Collection<String> countries) {
if (address == null) {
return false;
}
return countries.contains(countryCode(address));
}
private String countryCode(final InetAddress address) {
final com.maxmind.geoip.Country country =
LanternHub.getGeoIpLookup().getCountry(address);
LOG.info("Country is: {}", country.getName());
return country.getCode().trim();
}
}
|
package org.lightmare.config;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
import org.lightmare.cache.DeploymentDirectory;
/**
* Keeps keys and default values for configuration
*
* @author Levan
*
*/
public enum Config {
// Path where stored administrative users
ADMIN_USERS_PATH("adminUsersPath", "./config/admin/users.properties"),
// Netty server / client configuration properties for RPC calls
IP_ADDRESS("listeningIp", "0.0.0.0"),
PORT("listeningPort", "1199"), // port
BOSS_POOL("bossPoolSize", 1), // boss pool
WORKER_POOL_KEY("workerPoolSize", 3), // Worker pool
CONNECTION_TIMEOUT("timeout", 1000), // Connection timeout
// Properties for data source path and deployment path
DEMPLOYMENT_PATH("deploymentPath"),
DATA_SOURCE_PATH("dataSourcePath"); // data source path
// Default properties
public static final boolean SERVER_DEF = Boolean.TRUE;
public static final String DATA_SOURCE_PATH_DEF = "./ds";
// Properties which version of server is running remote it requires server
// client RPC infrastructure or local (embedded mode)
private static final String REMOTE_KEY = "remote";
private static final String SERVER_KEY = "server";
private static final String CLIENT_KEY = "client";
public static final Set<DeploymentDirectory> DEPLOYMENT_PATHS_DEF = new HashSet<DeploymentDirectory>(
Arrays.asList(new DeploymentDirectory("./deploy", Boolean.TRUE)));
public static final Set<String> DATA_SOURCES_PATHS_DEF = new HashSet<String>(
Arrays.asList("./ds"));
private static final String CONFIG_FILE = "./config/configuration.yaml";
// Configuration keys properties for deployment
private static final String DEPLOY_CONFIG_KEY = "deployConfiguration";
private static final String ADMIN_USER_PATH_KEY = "adminPath";
private static final String HOT_DEPLOYMENT_KEY = "hotDeployment";
private static final String WATCH_STATUS_KEY = "watchStatus";
private static final String LIBRARY_PATH_KEY = "libraryPaths";
// Persistence provider property keys
private static final String PERSISTENCE_CONFIG_KEY = "persistenceConfig";
private static final String SCAN_FOR_ENTITIES_KEY = "scanForEntities";
private static final String ANNOTATED_UNIT_NAME_KEY = "annotatedUnitName";
private static final String PERSISTENCE_XML_PATH_KEY = "persistanceXmlPath";
private static final String PERSISTENCE_XML_FROM_JAR_KEY = "persistenceXmlFromJar";
private static final String SWAP_DATASOURCE_KEY = "swapDataSource";
private static final String SCAN_ARCHIVES_KEY = "scanArchives";
private static final String POOLED_DATA_SOURCE_KEY = "pooledDataSource";
private static final String PERSISTENCE_PROPERTIES_KEY = "persistenceProperties";
// Connection pool provider property keys
private static final String POOL_CONFIG_KEY = "poolConfig";
private static final String POOL_PROPERTIES_PATH_KEY = "poolPropertiesPath";
private static final String POOL_PROVIDER_TYPE_KEY = "poolProviderType";
private static final String POOL_PROPERTIES_KEY = "poolProperties";
// Is configuration server or client (default is server)
private static boolean server = SERVER_DEF;
public String key;
public Object value;
private Config(String key) {
this.key = key;
}
private Config(String key, Object value) {
this(key);
this.value = value;
}
}
|
package org.measures.passage;
import com.d2fn.passage.sketches.SimpleTerrain01;
import com.d2fn.passage.sketches.TestSketch;
import javax.swing.*;
import java.awt.*;
/**
* Runner
* @author Dietrich Featherston
*/
public class Runner {
public Runner(final Sketch s) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
new SketchFrame(s).setVisible(true);
}
});
}
public static void main(String[] args) {
new Runner(new SimpleTerrain01());
// new Runner(new TestSketch());
}
private class SketchFrame extends JFrame {
SketchFrame(final Sketch s) {
super("passage");
getContentPane().setPreferredSize(new Dimension(s.getTargetWidth(), s.getTargetHeight()));
getContentPane().setSize(s.getTargetWidth(), s.getTargetHeight());
getContentPane().add(s, BorderLayout.CENTER);
pack();
setVisible(true);
s.init();
//setLocation(100, 100);
}
}
}
|
package org.monarch.golr;
import static com.google.common.collect.Collections2.transform;
import static java.util.Collections.singleton;
import java.io.IOException;
import java.io.StringWriter;
import java.io.Writer;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.ExecutionException;
import java.util.logging.Logger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.inject.Inject;
import org.apache.solr.client.solrj.SolrServerException;
import org.apache.solr.client.solrj.impl.HttpSolrClient;
import org.apache.solr.common.SolrInputDocument;
import org.apache.commons.lang3.ClassUtils;
import org.monarch.golr.beans.Closure;
import org.monarch.golr.beans.GolrCypherQuery;
import org.neo4j.graphdb.Direction;
import org.neo4j.graphdb.GraphDatabaseService;
import org.neo4j.graphdb.Label;
import org.neo4j.graphdb.Node;
import org.neo4j.graphdb.Path;
import org.neo4j.graphdb.PropertyContainer;
import org.neo4j.graphdb.Relationship;
import org.neo4j.graphdb.RelationshipType;
import org.neo4j.graphdb.Result;
import org.neo4j.graphdb.Transaction;
import org.neo4j.graphdb.traversal.Evaluators;
import org.neo4j.graphdb.traversal.TraversalDescription;
import org.neo4j.graphdb.traversal.Uniqueness;
import org.prefixcommons.CurieUtil;
import com.fasterxml.jackson.core.JsonFactory;
import com.fasterxml.jackson.core.JsonGenerator;
import com.google.common.base.Charsets;
import com.google.common.base.Function;
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
import com.google.common.collect.HashMultimap;
import com.google.common.collect.Multimap;
import com.google.common.io.Resources;
import io.scigraph.frames.CommonProperties;
import io.scigraph.frames.NodeProperties;
import io.scigraph.internal.CypherUtil;
import io.scigraph.internal.GraphApi;
import io.scigraph.internal.TinkerGraphUtil;
import io.scigraph.neo4j.DirectedRelationshipType;
import io.scigraph.neo4j.Graph;
import io.scigraph.neo4j.GraphUtil;
import io.scigraph.owlapi.OwlRelationships;
public class GolrLoader {
private static final Logger logger = Logger.getLogger(GolrLoader.class.getName());
private static final String EVIDENCE_GRAPH = "evidence_graph";
private static final String EVIDENCE_FIELD = "evidence";
private static final String SOURCE_FIELD = "source";
private static final String EVIDENCE_OBJECT_FIELD = "evidence_object";
private static final String DEFINED_BY = "is_defined_by";
private final GraphDatabaseService graphDb;
private final EvidenceProcessor processor;
private final Graph graph;
private final CypherUtil cypherUtil;
private final CurieUtil curieUtil;
private final GraphApi api;
private static final RelationshipType inTaxon =
RelationshipType.withName("http://purl.obolibrary.org/obo/RO_0002162");
private static final RelationshipType derivesFrom =
RelationshipType.withName("http://purl.obolibrary.org/obo/RO_0001000");
private static final RelationshipType derivesSeqFromGene =
RelationshipType.withName("http://purl.obolibrary.org/obo/GENO_0000639");
private static final RelationshipType hasGenotype =
RelationshipType.withName("http://purl.obolibrary.org/obo/GENO_0000222");
private static final String CHROMOSOME_TYPE = "http://purl.obolibrary.org/obo/SO_0000340";
private static final RelationshipType location = RelationshipType.withName("location");
private static final RelationshipType begin = RelationshipType.withName("begin");
private static final RelationshipType reference = RelationshipType.withName("reference");
private static final Label GENE_LABEL = Label.label("gene");
private static final Label VARIANT_LABEL = Label.label("sequence feature");
private static final Label GENOTYPE_LABEL = Label.label("genotype");
private final static int BATCH_SIZE = 10000;
private static final String ENTAILMENT_REGEX = "^\\[(\\w*):?([\\w:|\\.\\/
private static Pattern ENTAILMENT_PATTERN = Pattern.compile(ENTAILMENT_REGEX);
private Collection<RelationshipType> parts_of;
private Collection<RelationshipType> subSequenceOfs;
private Collection<RelationshipType> variants;
private TraversalDescription taxonDescription;
private TraversalDescription chromosomeDescription;
private TraversalDescription diseaseDescription;
private TraversalDescription orthologDescription;
private TraversalDescription phenotypeDescription;
private Collection<Node> chromsomeEntailment;
private TraversalDescription geneDescription;
private Collection<String> variantStrings;
@Inject
GolrLoader(GraphDatabaseService graphDb, Graph graph, CypherUtil cypherUtil, CurieUtil curieUtil,
EvidenceProcessor processor, GraphApi api) {
this.graphDb = graphDb;
this.cypherUtil = cypherUtil;
this.curieUtil = curieUtil;
this.graph = graph;
this.processor = processor;
this.api = api;
try (Transaction tx = graphDb.beginTx()) {
buildTraversals();
tx.success();
}
}
private void buildTraversals() {
parts_of = cypherUtil.getEntailedRelationshipTypes(
Collections.singleton("http://purl.obolibrary.org/obo/BFO_0000051"));
subSequenceOfs = cypherUtil.getEntailedRelationshipTypes(
Collections.singleton("http://purl.obolibrary.org/obo/RO_0002525"));
variants = cypherUtil.getEntailedRelationshipTypes(
Collections.singleton("http://purl.obolibrary.org/obo/GENO_0000418"));
taxonDescription = graphDb.traversalDescription().breadthFirst()
.relationships(OwlRelationships.OWL_EQUIVALENT_CLASS, Direction.BOTH)
.relationships(OwlRelationships.OWL_SAME_AS, Direction.BOTH)
.relationships(OwlRelationships.RDFS_SUBCLASS_OF, Direction.OUTGOING)
.relationships(OwlRelationships.RDF_TYPE, Direction.OUTGOING)
.relationships(inTaxon, Direction.OUTGOING).uniqueness(Uniqueness.RELATIONSHIP_GLOBAL);
for (RelationshipType part_of : parts_of) {
taxonDescription = taxonDescription.relationships(part_of, Direction.BOTH);
}
for (RelationshipType subSequenceOf : subSequenceOfs) {
taxonDescription = taxonDescription.relationships(subSequenceOf, Direction.INCOMING);
}
for (RelationshipType variant : variants) {
taxonDescription = taxonDescription.relationships(variant, Direction.OUTGOING);
}
taxonDescription = taxonDescription.relationships(hasGenotype, Direction.OUTGOING);
taxonDescription = taxonDescription.relationships(derivesFrom, Direction.OUTGOING);
chromosomeDescription = graphDb.traversalDescription().breadthFirst()
.relationships(OwlRelationships.OWL_EQUIVALENT_CLASS, Direction.BOTH)
.relationships(OwlRelationships.OWL_SAME_AS, Direction.BOTH)
.relationships(OwlRelationships.RDFS_SUBCLASS_OF, Direction.OUTGOING)
.relationships(OwlRelationships.RDF_TYPE, Direction.OUTGOING)
.relationships(location, Direction.OUTGOING).relationships(begin, Direction.OUTGOING)
.relationships(reference, Direction.OUTGOING);
orthologDescription = graphDb.traversalDescription().breadthFirst()
.relationships(RelationshipType.withName("http://purl.obolibrary.org/obo/RO_HOM0000017"))
.relationships(RelationshipType.withName("http://purl.obolibrary.org/obo/RO_HOM0000020"))
.evaluator(Evaluators.toDepth(1));
Optional<Long> nodeId = graph.getNode(CHROMOSOME_TYPE);
if (!nodeId.isPresent()) {
// TODO: Move all of this to some external configuration
return;
}
Node chromsomeParent = graphDb.getNodeById(nodeId.get());
chromsomeEntailment = api.getEntailment(chromsomeParent,
new DirectedRelationshipType(OwlRelationships.RDFS_SUBCLASS_OF, Direction.INCOMING), true);
geneDescription = graphDb.traversalDescription().depthFirst()
.relationships(OwlRelationships.OWL_SAME_AS, Direction.BOTH)
.relationships(OwlRelationships.OWL_EQUIVALENT_CLASS, Direction.BOTH);
for (RelationshipType part_of : parts_of) {
geneDescription = geneDescription.relationships(part_of, Direction.OUTGOING);
}
for (RelationshipType variant : variants) {
geneDescription = geneDescription.relationships(variant, Direction.OUTGOING);
}
geneDescription = geneDescription.relationships(derivesSeqFromGene, Direction.OUTGOING);
geneDescription = geneDescription.relationships(hasGenotype, Direction.OUTGOING);
geneDescription = geneDescription.relationships(derivesFrom, Direction.OUTGOING);
variantStrings = transform(variants, new Function<RelationshipType, String>() {
@Override
public String apply(RelationshipType type) {
return type.name();
}
});
diseaseDescription = graphDb.traversalDescription().depthFirst()
.relationships(RelationshipType.withName("http://purl.obolibrary.org/obo/RO_0002200"),
Direction.OUTGOING)
.relationships(RelationshipType.withName("http://purl.obolibrary.org/obo/RO_0002610"),
Direction.OUTGOING)
.relationships(RelationshipType.withName("http://purl.obolibrary.org/obo/RO_0002326"),
Direction.OUTGOING)
.evaluator(Evaluators.atDepth(1));
phenotypeDescription = graphDb.traversalDescription().depthFirst()
.relationships(RelationshipType.withName("http://purl.obolibrary.org/obo/RO_0002200"),
Direction.OUTGOING)
.relationships(RelationshipType.withName("http://purl.obolibrary.org/obo/RO_0002610"),
Direction.OUTGOING)
.relationships(RelationshipType.withName("http://purl.obolibrary.org/obo/RO_0002326"),
Direction.OUTGOING)
.evaluator(Evaluators.fromDepth(1)).evaluator(Evaluators.toDepth(2));
}
Optional<Node> getTaxon(Node source) {
for (Path path : taxonDescription.traverse(source)) {
if (path.length() > 0 && path.lastRelationship().isType(inTaxon)) {
return Optional.of(path.endNode());
}
}
return Optional.empty();
}
Optional<Node> getChromosome(Node source) {
for (Path path : chromosomeDescription.traverse(source)) {
if (path.length() > 0 && path.lastRelationship().isType(OwlRelationships.RDF_TYPE)) {
if (chromsomeEntailment.contains(path.endNode())) {
return Optional.of(path.lastRelationship().getOtherNode(path.endNode()));
}
}
}
return Optional.empty();
}
// TODO return array of all found nodes
// TODO and filter only cliqueLeaders
Optional<Node> getGene(Node source) {
for (Path path : geneDescription.traverse(source)) {
if (path.endNode().hasLabel(GENE_LABEL)) {
return Optional.of(path.endNode());
}
}
return Optional.empty();
}
Collection<Node> getOrthologs(Node source) throws IOException {
Collection<Node> orthologs = new HashSet<>();
for (Path path : orthologDescription.traverse(source)) {
if (path.endNode().hasLabel(GENE_LABEL) && path.endNode() != source) {
orthologs.add(path.endNode());
}
}
return orthologs;
}
Collection<Node> getDiseases(Node source) throws IOException {
String cypher = Resources.toString(Resources.getResource("disease.cypher"), Charsets.UTF_8);
Multimap<String, Object> params = HashMultimap.create();
params.put("id", source.getId());
Result result = cypherUtil.execute(cypher, params);
Collection<Node> diseases = new HashSet<>();
while (result.hasNext()) {
Map<String, Object> row = result.next();
diseases.add((Node) row.get("disease"));
}
return diseases;
}
Collection<Node> getPhenotypes(Node source) throws IOException {
String cypher = Resources.toString(Resources.getResource("phenotype.cypher"), Charsets.UTF_8);
Multimap<String, Object> params = HashMultimap.create();
params.put("id", source.getId());
Result result = cypherUtil.execute(cypher, params);
Collection<Node> phenotypes = new HashSet<>();
while (result.hasNext()) {
Map<String, Object> row = result.next();
phenotypes.add((Node) row.get("phenotype"));
}
return phenotypes;
}
LoadingCache<Node, Optional<Node>> taxonCache =
CacheBuilder.newBuilder().maximumSize(100_000).build(new CacheLoader<Node, Optional<Node>>() {
@Override
public Optional<Node> load(Node source) throws Exception {
return getTaxon(source);
}
});
LoadingCache<Node, Optional<Node>> chromosomeCache =
CacheBuilder.newBuilder().maximumSize(100_000).build(new CacheLoader<Node, Optional<Node>>() {
@Override
public Optional<Node> load(Node source) throws Exception {
return getChromosome(source);
}
});
LoadingCache<Node, Optional<Node>> geneCache =
CacheBuilder.newBuilder().maximumSize(100_000).build(new CacheLoader<Node, Optional<Node>>() {
@Override
public Optional<Node> load(Node source) throws Exception {
return getGene(source);
}
});
LoadingCache<Node, Collection<Node>> orthologCache = CacheBuilder.newBuilder()
.maximumSize(100_000).build(new CacheLoader<Node, Collection<Node>>() {
@Override
public Collection<Node> load(Node source) throws Exception {
return getOrthologs(source);
}
});
long process(GolrCypherQuery query, String solrServer, Object solrLock)
throws IOException, ExecutionException, ClassNotFoundException, SolrServerException {
return process(query, solrServer, solrLock, Optional.empty());
}
long process(GolrCypherQuery query, String solrServer, Object solrLock, Optional<String> metaSourceQuery)
throws IOException, ExecutionException, ClassNotFoundException, SolrServerException {
long recordCount = 0;
try (Transaction tx = graphDb.beginTx()) {
Result result = cypherUtil.execute(query.getQuery());
// Golr queries need to have the evidence graphs merged, whereas chromosome queries don't.
boolean isGolrQuery =
result.columns().contains("subject") && result.columns().contains("object");
if (isGolrQuery) {
recordCount = serializeGolrQuery(query, result, solrServer, solrLock, metaSourceQuery);
} else {
recordCount = serializedFeatureQuery(query, result, solrServer, solrLock, metaSourceQuery);
}
tx.success();
}
return recordCount;
}
private int serializeGolrQuery(GolrCypherQuery query, Result result,
String solrServer, Object solrLock, Optional<String> metaSourceQuery)
throws IOException, ClassNotFoundException, ExecutionException, SolrServerException {
SolrInputDocument resultDoc = new SolrInputDocument();
EvidenceGraphInfo resultGraph = null;
Pair<String, String> lastPair = new Pair<>("", "");
Collection<SolrInputDocument> docList = new ArrayList<>();
int recordCount = 0;
boolean isNewPair = true;
while (result.hasNext()) {
Map<String, Object> row = result.next();
String subjectIri = (String) ((Node) row.get("subject")).getProperty(NodeProperties.IRI);
String objectIri = (String) ((Node) row.get("object")).getProperty(NodeProperties.IRI);
Pair<String, String> pair = new Pair<>(subjectIri, objectIri);
if (recordCount == 0) {
lastPair = new Pair<>(subjectIri, objectIri);
}
if (!pair.equals(lastPair)) {
resultDoc = addEvidenceToDoc(resultDoc, resultGraph, metaSourceQuery);
docList.add(resultDoc);
if (docList.size() % BATCH_SIZE == 0) {
addAndCommitToSolr(solrServer, docList, solrLock);
docList.clear();
}
// Reset control flow variables
lastPair = pair;
isNewPair = true;
// Make new doc and graph
resultDoc = new SolrInputDocument();
resultGraph = null;
}
if (isNewPair) {
Set<Long> ignoredNodes = new HashSet<>();
Writer stringWriter = new StringWriter();
JsonGenerator stringGenerator = new JsonFactory().createGenerator(stringWriter);
TinkerGraphUtil tguEvidenceGraph = new TinkerGraphUtil(curieUtil);
stringGenerator.writeStartObject();
resultDoc = serializerRow(row, tguEvidenceGraph, ignoredNodes, query);
resultGraph = new EvidenceGraphInfo(tguEvidenceGraph.getGraph(), true, ignoredNodes);
isNewPair = false;
} else {
TinkerGraphUtil tguEvidenceGraph = new TinkerGraphUtil(EvidenceGraphInfo.toGraph(resultGraph.graphBytes), curieUtil);
Set<Long> ignoredNodes = resultGraph.ignoredNodes;
for (Entry<String, Object> entry : row.entrySet()) {
Object value = entry.getValue();
if (null == value) {
continue;
}
// Add evidence
if (value instanceof PropertyContainer) {
tguEvidenceGraph.addElement((PropertyContainer) value);
} else if (value instanceof Path) {
tguEvidenceGraph.addPath((Path) value);
} else if (value instanceof Node) {
ignoredNodes.add(((Node) value).getId());
}
}
resultGraph =
new EvidenceGraphInfo(tguEvidenceGraph.getGraph(), resultGraph.emitEvidence, ignoredNodes);
}
if (!result.hasNext()) {
resultDoc = addEvidenceToDoc(resultDoc, resultGraph, metaSourceQuery);
docList.add(resultDoc);
}
recordCount++;
}
if (docList.size() > 0) {
addAndCommitToSolr(solrServer, docList, solrLock);
docList.clear();
}
return recordCount;
}
private SolrInputDocument addEvidenceToDoc(SolrInputDocument resultDoc,
EvidenceGraphInfo resultGraph, Optional<String> metaSourceQuery)
throws IOException, ClassNotFoundException {
ClosureUtil closureUtil = new ClosureUtil(graphDb, curieUtil);
SolrDocUtil docUtil = new SolrDocUtil(closureUtil);
com.tinkerpop.blueprints.Graph evidenceGraph =
EvidenceGraphInfo.toGraph(resultGraph.graphBytes);
processor.addAssociations(evidenceGraph);
String evidenceBlob = processor.getEvidenceGraph(evidenceGraph, metaSourceQuery);
if (!resultDoc.getFieldValue("subject_category").equals("ontology")
|| !resultDoc.getFieldValue("object_category").equals("ontology")){
//TODO add exclude evidence to configuration
resultDoc.addField(EVIDENCE_GRAPH, evidenceBlob);
List<Closure> evidenceObjectClosure =
processor.getEvidenceObject(evidenceGraph, resultGraph.ignoredNodes);
docUtil.writeQuint(EVIDENCE_OBJECT_FIELD, evidenceObjectClosure, resultDoc);
List<Closure> evidenceClosure = processor.getEvidence(evidenceGraph);
docUtil.writeQuint(EVIDENCE_FIELD, evidenceClosure, resultDoc);
}
List<Closure> sourceClosure = processor.getSource(evidenceGraph);
docUtil.writeQuint(SOURCE_FIELD, sourceClosure, resultDoc);
resultDoc.addField(DEFINED_BY, processor.getDefinedBys(evidenceGraph));
return resultDoc;
}
private static void addAndCommitToSolr(String solrServer,
Collection<SolrInputDocument>docList, Object solrLock) throws SolrServerException, IOException {
synchronized (solrLock) {
HttpSolrClient solrClient = new HttpSolrClient.Builder(solrServer).build();
// Set the socket and connect timeouts the same as solr.jetty.http.idleTimeout
solrClient.setSoTimeout(200000);
solrClient.setConnectionTimeout(200000);
try {
solrClient.add(docList);
} catch (IOException|SolrServerException e) {
logger.warning("Caught: " + e);
logger.info("Retrying add");
solrClient.add(docList);
}
solrClient.commit();
solrClient.close();
}
}
private long serializedFeatureQuery(GolrCypherQuery query, Result result,
String solrServer, Object solrLock, Optional<String> metaSourceQuery)
throws IOException, ExecutionException, SolrServerException {
int recordCount = 0;
Collection<SolrInputDocument> docList = new ArrayList<SolrInputDocument>();
while (result.hasNext()) {
SolrInputDocument doc = new SolrInputDocument();
Set<Long> ignoredNodes = new HashSet<>();
TinkerGraphUtil tguEvidenceGraph = new TinkerGraphUtil(curieUtil);
recordCount++;
Map<String, Object> row = result.next();
doc = serializerRow(row, tguEvidenceGraph, ignoredNodes, query);
docList.add(doc);
if (docList.size() != 0 && docList.size() % BATCH_SIZE == 0) {
addAndCommitToSolr(solrServer, docList, solrLock);
docList.clear();
}
}
if (docList.size() > 0) {
addAndCommitToSolr(solrServer, docList, solrLock);
docList.clear();
}
return recordCount;
}
private Set<DirectedRelationshipType> resolveRelationships(String key, String value) {
Set<DirectedRelationshipType> rels = new HashSet<>();
String cypherIn = String.format("[%s:%s]", key, value);
String cypherOut = cypherUtil.resolveRelationships(cypherIn);
Matcher m = ENTAILMENT_PATTERN.matcher(cypherOut);
while (m.find()) {
String types = m.group(2);
String[] cypherRels = types.split("\\|");
for (String cypherRel : cypherRels) {
String unquotedCypherRel = cypherRel.replaceAll("^`|`$","");
unquotedCypherRel = curieUtil.getIri(unquotedCypherRel).orElse(unquotedCypherRel);
RelationshipType relType = RelationshipType.withName(unquotedCypherRel);
Direction direction = Direction.OUTGOING;
if (relType.equals(OwlRelationships.OWL_EQUIVALENT_CLASS)
|| relType.equals(OwlRelationships.OWL_SAME_AS)) {
direction = Direction.BOTH;
}
DirectedRelationshipType dirRelType = new DirectedRelationshipType(relType, direction);
rels.add(dirRelType);
}
}
return rels;
}
SolrInputDocument serializerRow(Map<String, Object> row,
TinkerGraphUtil tguEvidenceGraph, Set<Long> ignoredNodes, GolrCypherQuery query)
throws IOException, ExecutionException {
boolean emitEvidence = true;
SolrInputDocument doc = new SolrInputDocument();
ClosureUtil closureUtil = new ClosureUtil(graphDb, curieUtil);
SolrDocUtil docUtil = new SolrDocUtil(closureUtil);
for (Entry<String, Object> entry : row.entrySet()) {
String key = entry.getKey();
Object value = entry.getValue();
if (null == value) {
continue;
}
// Add evidence
if (value instanceof PropertyContainer) {
tguEvidenceGraph.addElement((PropertyContainer) value);
} else if (value instanceof Path) {
tguEvidenceGraph.addPath((Path) value);
} else if (value instanceof Node) {
ignoredNodes.add(((Node) value).getId());
}
if (value instanceof Node) {
// TODO: Clean this up
if ("subject".equals(key) || "object".equals(key)) {
Node node = (Node) value;
Optional<Node> taxon = taxonCache.get(node);
if (taxon.isPresent()) {
docUtil.addNodes(key + "_taxon", singleton((Node) taxon.get()), doc);
}
if (node.hasLabel(GENE_LABEL) || node.hasLabel(VARIANT_LABEL)
|| node.hasLabel(GENOTYPE_LABEL)) {
// Attempt to add gene and chromosome for monarch-initiative/monarch-app/#746
if (node.hasLabel(GENE_LABEL)) {
docUtil.addNodes(key + "_gene", singleton((Node) node), doc);
} else {
Optional<Node> gene = geneCache.get(node);
if (gene.isPresent()) {
docUtil.addNodes(key + "_gene", singleton((Node) gene.get()), doc);
}
}
Optional<Node> chromosome = chromosomeCache.get(node);
if (chromosome.isPresent()) {
docUtil.addNodes(key + "_chromosome", singleton((Node) chromosome.get()), doc);
}
}
}
if ("subject".equals(key)) {
Collection<Node> orthologs = orthologCache.get((Node) value);
Collection<String> orthologsId = transform(orthologs, new Function<Node, String>() {
@Override
public String apply(Node node) {
String iri = GraphUtil.getProperty(node, NodeProperties.IRI, String.class).get();
return curieUtil.getCurie(iri).orElse(iri);
}
});
doc.addField("subject_ortholog_closure", new ArrayList<String>(orthologsId));
}
if ("feature".equals(key)) {
// Add disease and phenotype for feature
docUtil.addNodes("disease", getDiseases((Node) value), doc);
docUtil.addNodes("phenotype", getPhenotypes((Node) value), doc);
}
if (query.getCollectedTypes().containsKey(key)) {
docUtil.addNodes(key, singleton((Node) value), query.getCollectedTypes().get(key), doc);
}
else if ("subject".equals(key) || "object".equals(key) || "relation".equals(key) || "evidence".equals(key)) {
Set<DirectedRelationshipType> closureTypes = new HashSet<>();
closureTypes.addAll(SolrDocUtil.DEFAULT_CLOSURE_TYPES);
if ("subject".equals(key) && query.getSubjectClosure() != null) {
Set<DirectedRelationshipType> rels = resolveRelationships("subject_closure", query.getSubjectClosure());
closureTypes.clear();
closureTypes.addAll(rels);
// Add all equivalent IDs to subject
List<Closure> closures = new ArrayList<>();
closures.add(closureUtil.getClosure((Node) value, SolrDocUtil.EQUIVALENT_EDGES));
docUtil.addClosure("subject_eq", ClosureUtil.collectIdClosure(closures), doc);
}
if ("object".equals(key) && query.getObjectClosure() != null) {
Set<DirectedRelationshipType> rels = resolveRelationships("object_closure", query.getObjectClosure());
closureTypes.clear();
closureTypes.addAll(rels);
// Add all equivalent IDs to object
List<Closure> closures = new ArrayList<>();
closures.add(closureUtil.getClosure((Node) value, SolrDocUtil.EQUIVALENT_EDGES));
docUtil.addClosure("object_eq", ClosureUtil.collectIdClosure(closures), doc);
}
if ("relation".equals(key) && query.getRelationClosure() != null) {
Set<DirectedRelationshipType> rels = resolveRelationships("relation_closure", query.getRelationClosure());
closureTypes.clear();
closureTypes.addAll(rels);
}
if ("evidence".equals(key) && query.getEvidenceClosure() != null) {
Set<DirectedRelationshipType> rels = resolveRelationships("evidence_closure", query.getEvidenceClosure());
closureTypes.clear();
closureTypes.addAll(rels);
}
docUtil.addNodes(key, singleton((Node) value), closureTypes, doc);
}
else {
docUtil.addNodes(key, singleton((Node) value), doc);
}
} else if (value instanceof Relationship) {
String objectPropertyIri =
GraphUtil.getProperty((Relationship) value, CommonProperties.IRI, String.class).get();
Node objectProperty = graphDb.getNodeById(graph.getNode(objectPropertyIri).get());
docUtil.addNodes(key, singleton((Node) objectProperty), doc);
} else if (ClassUtils.isPrimitiveOrWrapper(value.getClass()) || value instanceof String) {
// Serialize primitive types and Strings
if ((key.equals("subject_category") || key.equals("object_category"))
&& value.equals("ontology")) {
emitEvidence = false;
}
doc.addField(key, value);
}
}
return doc;
}
}
|
package org.nikko.humanize;
import static java.lang.String.format;
import static org.nikko.humanize.util.Constants.*;
import java.math.BigDecimal;
import java.text.BreakIterator;
import java.text.ChoiceFormat;
import java.text.DateFormat;
import java.text.DecimalFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.Locale;
import java.util.ServiceLoader;
import java.util.concurrent.Callable;
import org.nikko.humanize.spi.Message;
import org.nikko.humanize.spi.context.Context;
import org.nikko.humanize.spi.context.ContextFactory;
import org.nikko.humanize.util.RelativeDate;
/**
* <p>
* Facility for adding a "human touch" to data. It is thread-safe and supports
* per-thread internationalization.
* </p>
*
* @author mfornos
*
*/
public final class Humanize {
private static final ContextFactory contextFactory = loadContextFactory();
private static final ThreadLocal<Context> context = new ThreadLocal<Context>() {
protected Context initialValue() {
return contextFactory.createContext();
};
};
/**
* <p>
* Converts a given number to a string preceded by the corresponding binary
* International System of Units (SI) prefix.
* </p>
*
* <table border="1" width="100%">
* <tr>
* <th>Input</th>
* <th>Output</th>
* </tr>
* <tr>
* <td>2</td>
* <td>"2 bytes"</td>
* </tr>
* <tr>
* <td>1536</td>
* <td>"1.5 kB"</td>
* </tr>
* <tr>
* <td>5242880</td>
* <td>"5.00 MB"</td>
* </tr>
* <tr>
* <td>1325899906842624L</td>
* <td>"1.18 PB"</td>
* </tr>
* </table>
*
* @param value
* Number to be converted
* @return The number preceded by the corresponding binary SI prefix
*/
public static String binaryPrefix(Number value) {
long v = value.longValue();
if (v < 0)
return value.toString();
for (Long num : binPrexies.keySet())
if (num <= v)
return format(binPrexies.get(num), (v >= 1024) ? v / (float) num : v);
return value.toString(); // unreachable
}
public static String formatCurrency(Number value) {
DecimalFormat decf = (DecimalFormat) context.get().getCurrencyFormat();
char decsep = decf.getDecimalFormatSymbols().getDecimalSeparator();
String fmtd = decf.format(value);
return fmtd.replaceAll("\\" + decsep + "00", EMPTY_STRING);
}
/**
* <p>
* Same as {@link #formatCurrency(Number) formatCurrency} for the specified
* locale.
* </p>
*
* @param value
* Number to be formatted
* @param locale
* Target locale
* @return String representing the monetary amount
*/
public static String formatCurrency(final Number value, final Locale locale) {
return withinLocale(new Callable<String>() {
public String call() {
return formatCurrency(value);
}
}, locale);
}
/**
* <p>
* Same as {@link #formatDate(int, Date) formatDate} with DateFormat.SHORT
* style.
* </p>
*
* @param value
* Date to be formatted
* @return String representation of the date
*/
public static String formatDate(Date value) {
return formatDate(DateFormat.SHORT, value);
}
/**
* <p>
* Formats the given date with the specified style.
* </p>
*
* @param style
* DateFormat style
* @param value
* Date to be formatted
* @return String representation of the date
*/
public static String formatDate(int style, Date value) {
return context.get().formatDate(style, value);
}
/**
* <p>
* Formats the given number to the standard decimal format for the default
* locale.
* </p>
*
* @param value
* Number to be formatted
* @return Standard localized format representation
*/
public static String formatDecimal(Number value) {
return context.get().formatDecimal(value);
}
/**
* <p>
* Same as {@link #formatDecimal(Number) formatDecimal} for the specified
* locale.
* </p>
*
* @param value
* Number to be formatted
* @param locale
* Target locale
* @return Standard localized format representation
*/
public static String formatDecimal(final Number value, final Locale locale) {
return withinLocale(new Callable<String>() {
public String call() {
return formatDecimal(value);
}
}, locale);
}
/**
* <p>
* Creates a RelativeDate instance. It is useful to compute multiple
* relative dates with the same instance.
* </p>
*
* @return RelativeDate instance
*/
public static RelativeDate getRelativeDateInstance() {
return context.get().getRelativeDate();
}
/**
* <p>
* Same as {@link #getRelativeDateInstance() getRelativeDateInstance} for
* the specified locale.
* </p>
*
* @param locale
* Target locale
* @return RelativeDate instance
*/
public static RelativeDate getRelativeDateInstance(final Locale locale) {
return withinLocale(new Callable<RelativeDate>() {
public RelativeDate call() throws Exception {
return context.get().getRelativeDate();
}
}, locale);
}
/**
* <p>
* Same as {@link #naturalDay(int, Date) naturalDay} with DateFormat.SHORT
* style.
* </p>
*
* @param value
* Date to be converted
* @return String with "today", "tomorrow" or "yesterday" compared to
* current day. Otherwise, returns a string formatted according to a
* locale sensitive DateFormat.
*/
public static String naturalDay(Date value) {
return naturalDay(DateFormat.SHORT, value);
}
/**
* <p>
* For dates that are the current day or within one day, return "today",
* "tomorrow" or "yesterday", as appropriate. Otherwise, returns a string
* formatted according to a locale sensitive DateFormat.
* </p>
*
* @param style
* DateFormat style
* @param value
* Date to be converted
* @return String with "today", "tomorrow" or "yesterday" compared to
* current day. Otherwise, returns a string formatted according to a
* locale sensitive DateFormat.
*/
public static String naturalDay(int style, Date value) {
Date today = new Date();
long delta = value.getTime() - today.getTime();
long days = delta / ND_FACTOR;
if (days == 0)
return context.get().getMessage("today");
else if (days == 1)
return context.get().getMessage("tomorrow");
else if (days == -1)
return context.get().getMessage("yesterday");
return formatDate(style, value);
}
/**
* <p>
* Same as {@link #naturalTime(Date, Date) naturalTime} with current date as
* reference.
* </p>
*
* @param duration
* Date to be used as duration from current date
* @return String representing the relative date
*/
public static String naturalTime(Date duration) {
return context.get().formatRelativeDate(duration);
}
/**
* <p>
* Computes both past and future relative dates.
* </p>
*
* <p>
* E.g. "one day ago", "one day from now", "10 years ago", "3 minutes from
* now", "right now" and so on.
* </p>
*
* @param reference
* Date to be used as reference
* @param duration
* Date to be used as duration from reference
* @return String representing the relative date
*/
public static String naturalTime(Date reference, Date duration) {
return context.get().formatRelativeDate(reference, duration);
}
/**
* <p>
* Same as {@link #naturalTime(Date, Date) naturalTime} for the specified
* locale.
* </p>
*
* @param reference
* Date to be used as reference
* @param duration
* Date to be used as duration from reference
* @param locale
* Target locale
* @return String representing the relative date
*/
public static String naturalTime(final Date reference, final Date duration, final Locale locale) {
return withinLocale(new Callable<String>() {
public String call() {
return naturalTime(reference, duration);
}
}, locale);
}
/**
* Same as {@link #naturalTime(Date) naturalTime} for the specified locale.
*
* @param duration
* Date to be used as duration from current date
* @param locale
* Target locale
* @return String representing the relative date
*/
public static String naturalTime(final Date duration, final Locale locale) {
return naturalTime(new Date(), duration, locale);
}
/**
* <p>
* Converts a number to its ordinal as a string.
* </p>
*
* <table border="1" width="100%">
* <tr>
* <th>Input</th>
* <th>Output</th>
* </tr>
* <tr>
* <td>1</td>
* <td>"1st"</td>
* </tr>
* <tr>
* <td>2</td>
* <td>"2nd"</td>
* </tr>
* <tr>
* <td>3</td>
* <td>"3rd"</td>
* </tr>
* <tr>
* <td>4</td>
* <td>"4th"</td>
* </tr>
* <tr>
* <td>1002</td>
* <td>"1002nd"</td>
* </tr>
* <tr>
* <td>2012</td>
* <td>"2012th"</td>
* </tr>
* </table>
*
* @param value
* Number to be converted
* @return String representing the number as ordinal
*/
public static String ordinalize(Number value) {
int v = value.intValue();
int vc = v % 100;
if (vc > 10 && vc < 14)
return format(ORDINAL_FMT, v, context.get().ordinalSuffix(0));
return format(ORDINAL_FMT, v, context.get().ordinalSuffix(v % 10));
}
/**
* <p>
* Same as {@link #ordinalize(Number) ordinalize} for the specified locale.
* </p>
*
* @param value
* Number to be converted
* @param locale
* Target locale
* @return String representing the number as ordinal
*/
public static String ordinalize(final Number value, final Locale locale) {
return withinLocale(new Callable<String>() {
public String call() {
return ordinalize(value);
}
}, locale);
}
/**
* <p>
* Constructs a message with pluralization logic from the given template.
* </p>
*
* Example:
*
* <pre>
* <code>
* Message msg = pluralize("There {0} on {1}.::are no files::is one file::are {2} files");
*
* msg.render(0, "disk"); // == "There are no files on disk."
* msg.render(1, "disk"); // == "There is one file on disk."
* msg.render(1000, "disk"); // == "There are 1,000 files on disk."
* </code>
* </pre>
*
* @param template
* String of tokens delimited by '::'
*
* @return Message instance prepared to generate pluralized strings
*/
public static Message pluralize(String template) {
String[] tokens = template.split("\\s*\\:{2}\\s*");
if (tokens.length < 3)
throw new RuntimeException(format("Template '%s' must declare at least 3 tokens", template));
return pluralize(tokens[0], Arrays.copyOfRange(tokens, 1, tokens.length));
}
/**
* <p>
* Constructs a message with pluralization logic by the means of
* ChoiceFormat.
* </p>
*
* @param pattern
* Base pattern
* @param choices
* Values that match the pattern
* @return Message instance prepared to generate pluralized strings
*/
public static Message pluralize(String pattern, String... choices) {
double[] indexes = new double[choices.length];
for (int i = 0; i < choices.length; i++)
indexes[i] = i;
ChoiceFormat choiceForm = new ChoiceFormat(indexes, choices);
Message format = context.get().getFormat();
format.applyPattern(pattern);
format.setFormat(0, choiceForm);
return format;
}
/**
* <p>
* Converts a big number to a friendly text representation. Accepts values
* ranging from thousands to googols. Uses BigDecimal.
* </p>
*
* @param value
* Number to be converted
* @return Friendly text representation of the given value
*/
public static String spellBigNumber(Number value) {
BigDecimal v = new BigDecimal(value.toString());
if (THOUSAND.compareTo(v.abs()) > 0)
return value.toString();
boolean isPlural = needPlural(v.unscaledValue().intValue());
for (BigDecimal bigNum : bigDecExponents.keySet())
if (bigNum.multiply(THOUSAND).compareTo(v.abs()) > 0)
return context.get().formatMessage(
(isPlural) ? bigDecExponents.get(bigNum) + ".pl" : bigDecExponents.get(bigNum),
v.divide(bigNum));
return value.toString();
}
/**
* <p>
* Same as {@link #spellBigNumber(Number) spellBigNumber} for the specified
* locale.
* </p>
*
* @param value
* Number to be converted
* @param locale
* Target locale
* @return Friendly text representation of the given value
*/
public static String spellBigNumber(final Number value, final Locale locale) {
return withinLocale(new Callable<String>() {
public String call() {
return spellBigNumber(value);
}
}, locale);
}
/**
* <p>
* For decimal digits [0-9], returns the number spelled out. Otherwise,
* returns the number as string.
* </p>
*
* <table border="1" width="100%">
* <tr>
* <th>Input</th>
* <th>Output</th>
* </tr>
* <tr>
* <td>1</td>
* <td>"one"</td>
* </tr>
* <tr>
* <td>2</td>
* <td>"two"</td>
* </tr>
* <tr>
* <td>10</td>
* <td>"10"</td>
* </tr>
* </table>
*
* @param value
* Decimal digit
* @return String representing the number spelled out
*/
public static String spellDigit(Number value) {
int v = value.intValue();
if (v < 0 || v > 9)
return value.toString();
return context.get().digitStrings(v);
}
/**
* <p>
* Same as {@link #spellDigit(Number) spellDigit} for the specified locale.
* </p>
*
* @param value
* Decimal digit
* @param locale
* Target locale
* @return String representing the number spelled out
*/
public static String spellDigit(final Number value, final Locale locale) {
return withinLocale(new Callable<String>() {
public String call() {
return spellDigit(value);
}
}, locale);
}
/**
* <p>
* Capitalize all the words, and replace some characters in the string to
* create a nice looking title.
* </p>
*
* <table border="1" width="100%">
* <tr>
* <th>Input</th>
* <th>Output</th>
* </tr>
* <tr>
* <td>"the_jackie_gleason show"</td>
* <td>"The Jackie Gleason Show"</td>
* </tr>
* <tr>
* <td>"first annual report (CD) 2001"</td>
* <td>"First Annual Report (CD) 2001"</td>
* </tr>
* </table>
*
* @param text
* Text to be converted
*
* @return Nice looking title
*/
// TODO add non capitalizable words by locale
public static String titleize(String text) {
StringBuilder sb = new StringBuilder(text.length());
boolean capitalize = true; // To get the first character right
for (int i = 0; i < text.length(); i++) {
char ch = text.charAt(i);
if (Character.isWhitespace(ch)) {
sb.append(' ');
capitalize = true;
} else if (ch == '_') {
sb.append(' ');
capitalize = true;
} else if (capitalize) {
sb.append(Character.toUpperCase(ch));
capitalize = false;
} else {
sb.append(ch);
}
}
return sb.toString();
}
/**
* <p>
* Converts a camel case string into a human-readable name.
* </p>
*
* <table border="1" width="100%">
* <tr>
* <th>Input</th>
* <th>Output</th>
* </tr>
* <tr>
* <td>"MyClass"</td>
* <td>"My Class"</td>
* </tr>
* <tr>
* <td>"GL11Version"</td>
* <td>"GL 11 Version"</td>
* </tr>
* <tr>
* <td>"AString"</td>
* <td>"A String"</td>
* </tr>
* <tr>
* <td>"SimpleXMLParser"</td>
* <td>"Simple XML Parser"</td>
* </tr>
* </table>
*
* @param words
* String to be converted
* @return words converted to human-readable name
*/
public static String uncamelize(String words) {
return SPLIT_CAMEL_REGEX.matcher(words).replaceAll(SPACE_STRING);
}
/**
* <p>
* Truncate a string to the closest word boundary after a number of
* characters.
* </p>
*
* @param value
* Text to be truncated
* @param len
* Number of characters
* @return String truncated to the closes word boundary
*/
public static String wordWrap(String value, int len) {
if (len < 0 || value.length() <= len)
return value;
BreakIterator bi = BreakIterator.getWordInstance(context.get().getLocale());
bi.setText(value);
return value.substring(0, bi.following(len));
}
private static ContextFactory loadContextFactory() {
ServiceLoader<ContextFactory> ldr = ServiceLoader.load(ContextFactory.class);
for (ContextFactory factory : ldr) {
return factory;
}
throw new RuntimeException("No ContextFactory was found");
}
/**
* <p>
* Checks if the given integer contains any digit greater than 1.
* </p>
*
* @param n
* Number to be evaluated
* @return true if the number contains a digit greater than 1, false
* otherwise
*/
private static boolean needPlural(int n) {
int tmp = 0;
n = Math.abs(n);
while (n > 0) {
tmp = n % 10;
if (tmp > 1)
return true;
n /= 10;
}
return false;
}
/**
* <p>
* Wraps the given operation on a context with the specified locale.
* </p>
*
* @param operation
* Operation to be performed
* @param locale
* Target locale
* @return Result of the operation
*/
private static <T> T withinLocale(Callable<T> operation, Locale locale) {
Context ctx = context.get();
Locale oldLocale = ctx.getLocale();
try {
ctx.setLocale(locale);
return operation.call();
} catch (Exception e) {
throw new RuntimeException(e);
} finally {
ctx.setLocale(oldLocale);
context.set(ctx);
}
}
private Humanize() {
}
}
|
package org.oakgp.node;
import java.util.function.Predicate;
import org.oakgp.Arguments;
import org.oakgp.Assignments;
import org.oakgp.Type;
import org.oakgp.function.Function;
/** Contains a function (operator) and the arguments (operands) to apply to it. */
public final class FunctionNode implements Node {
private static final int PRIMES[] = { 2, 3, 5, 7, 11, 13, 19 };
private final Function function;
private final Arguments arguments;
private final int nodeCount;
private final int hashCode;
/**
* Constructs a new {@code FunctionNode} with the specified function function and arguments.
*
* @param function
* the function to associate with this {@code FunctionNode}
* @param arguments
* the arguments (i.e. operands) to apply to {@code function} when evaluating this {@code FunctionNode}
*/
public FunctionNode(Function function, Node... arguments) {
this(function, Arguments.createArguments(arguments));
}
/**
* Constructs a new {@code FunctionNode} with the specified function function and arguments.
*
* @param function
* the function to associate with this {@code FunctionNode}
* @param arguments
* the arguments (i.e. operands) to apply to {@code function} when evaluating this {@code FunctionNode}
*/
public FunctionNode(Function function, Arguments arguments) {
this.function = function;
this.arguments = arguments;
this.nodeCount = calculateNodeCount(arguments);
this.hashCode = (function.getClass().getName().hashCode() * 31) * createHashCode(arguments, nodeCount);
}
private static int calculateNodeCount(Arguments arguments) {
int total = 1;
for (int i = 0; i < arguments.getArgCount(); i++) {
total += arguments.getArg(i).getNodeCount();
}
return total;
}
private static int createHashCode(Arguments arguments, int nodeCount) {
int hashCode = 0;
for (int i = 0; i < arguments.getArgCount(); i++) {
// TODO avoid array index out of bounds when arg count > PRIMES.length
hashCode += arguments.getArg(i).hashCode() * (PRIMES[i] + nodeCount);
}
return hashCode;
}
public Function getFunction() {
return function;
}
public Arguments getArguments() {
return arguments;
}
@Override
public Object evaluate(Assignments assignments) {
return function.evaluate(arguments, assignments);
}
@Override
public Node replaceAt(int index, java.util.function.Function<Node, Node> replacement) {
int total = 0;
for (int i = 0; i < arguments.getArgCount(); i++) {
Node node = arguments.getArg(i);
int c = node.getNodeCount();
if (total + c > index) {
return new FunctionNode(function, arguments.replaceAt(i, node.replaceAt(index - total, replacement)));
} else {
total += c;
}
}
return replacement.apply(this);
}
@Override
public Node replaceAt(int index, java.util.function.Function<Node, Node> replacement, Predicate<Node> treeWalkerStrategy) {
int total = 0;
for (int i = 0; i < arguments.getArgCount(); i++) {
Node node = arguments.getArg(i);
int c = node.getNodeCount(treeWalkerStrategy);
if (total + c > index) {
return new FunctionNode(function, arguments.replaceAt(i, node.replaceAt(index - total, replacement, treeWalkerStrategy)));
} else {
total += c;
}
}
return replacement.apply(this);
}
@Override
public Node getAt(int index) {
int total = 0;
for (int i = 0; i < arguments.getArgCount(); i++) {
Node node = arguments.getArg(i);
int c = node.getNodeCount();
if (total + c > index) {
return arguments.getArg(i).getAt(index - total);
} else {
total += c;
}
}
return this;
}
@Override
public Node getAt(int index, Predicate<Node> treeWalkerStrategy) {
int total = 0;
for (int i = 0; i < arguments.getArgCount(); i++) {
Node node = arguments.getArg(i);
int c = node.getNodeCount(treeWalkerStrategy);
if (total + c > index) {
return arguments.getArg(i).getAt(index - total, treeWalkerStrategy);
} else {
total += c;
}
}
if (!treeWalkerStrategy.test(this)) {
throw new IllegalStateException();
}
return this;
}
@Override
public int getNodeCount() {
return nodeCount;
}
@Override
public int getNodeCount(Predicate<Node> treeWalkerStrategy) {
int total = treeWalkerStrategy.test(this) ? 1 : 0;
for (int i = 0; i < arguments.getArgCount(); i++) {
total += arguments.getArg(i).getNodeCount(treeWalkerStrategy);
}
return total;
}
@Override
public int getHeight() {
// TODO cache on first call
int height = 0;
for (int i = 0; i < arguments.getArgCount(); i++) {
height = Math.max(height, arguments.getArg(i).getHeight());
}
return height + 1;
}
@Override
public Type getType() {
return function.getSignature().getReturnType();
}
@Override
public NodeType getNodeType() {
return NodeType.FUNCTION;
}
@Override
public int hashCode() {
return hashCode;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
} else if (hashCode() != o.hashCode()) {
return false;
} else if (o instanceof FunctionNode) {
FunctionNode fn = (FunctionNode) o;
// TODO see how often we return false when we get here - as that indicates hashCode() could be improved
return this.function.getClass().equals(fn.function.getClass()) && this.arguments.equals(fn.arguments);
} else {
return false;
}
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append('(').append(function.getClass().getName());
for (int i = 0; i < arguments.getArgCount(); i++) {
sb.append(' ').append(arguments.getArg(i));
}
return sb.append(')').toString();
}
}
|
package org.swingeasy;
import java.util.Comparator;
import java.util.List;
import java.util.Vector;
import org.apache.commons.lang.builder.CompareToBuilder;
import ca.odell.glazedlists.gui.AdvancedTableFormat;
import ca.odell.glazedlists.gui.WritableTableFormat;
/**
* @author Jurgen
*/
@SuppressWarnings("rawtypes")
public class ETableHeaders<T> implements WritableTableFormat<ETableRecord<T>>, AdvancedTableFormat<ETableRecord<T>> {
protected final List<String> columnNames = new Vector<String>();
protected final List<Class> columnClasses = new Vector<Class>();
protected final List<Boolean> editable = new Vector<Boolean>();
/**
* Instantieer een nieuwe Headers
*
* @param names
*/
public ETableHeaders() {
super();
}
public ETableHeaders(String... cols) {
for (String col : cols) {
this.add(col);
}
}
/**
* JDOC
*
* @param column
*/
public void add(String column) {
this.add(column, Object.class);
}
/**
*
* JDOC
*
* @param column
* @param clazz
*/
public void add(String column, Class<?> clazz) {
this.add(column, clazz, Boolean.FALSE);
}
/**
*
* JDOC
*
* @param column
* @param clazz
* @param edit
*/
public void add(String column, Class<?> clazz, Boolean edit) {
this.columnNames.add(column);
this.columnClasses.add(clazz);
this.editable.add(edit);
}
/**
*
* @see ca.odell.glazedlists.gui.AdvancedTableFormat#getColumnClass(int)
*/
@Override
public Class<?> getColumnClass(int columnIndex) {
if (this.columnNames.size() == 0) {
return Object.class;
}
Class<?> clas = this.columnClasses.get(columnIndex);
// System.out.println("ETableHeaders.getColumnClass(" + columnIndex + ")=" + clas);
return clas;
}
/**
*
* @see ca.odell.glazedlists.gui.AdvancedTableFormat#getColumnComparator(int)
*/
@Override
public Comparator<?> getColumnComparator(int column) {
return new Comparator<Object>() {
@Override
public int compare(Object o1, Object o2) {
return new CompareToBuilder().append(o1, o2).toComparison();
}
};
}
/**
* @see ca.odell.glazedlists.gui.TableFormat#getColumnCount()
*/
@Override
public int getColumnCount() {
return this.columnNames.size();
}
/**
* @see ca.odell.glazedlists.gui.TableFormat#getColumnName(int)
*/
@Override
public String getColumnName(int column) {
return this.columnNames.get(column);
}
public List<String> getColumnNames() {
return this.columnNames;
}
/**
* @see ca.odell.glazedlists.gui.TableFormat#getColumnValue(java.lang.Object, int)
*/
@Override
public Object getColumnValue(ETableRecord row, int column) {
return row.get(column);
}
/**
*
* @see ca.odell.glazedlists.gui.WritableTableFormat#isEditable(java.lang.Object, int)
*/
@Override
public boolean isEditable(ETableRecord baseObject, int column) {
return Boolean.TRUE.equals(this.editable.get(column));
}
/**
*
* @see ca.odell.glazedlists.gui.WritableTableFormat#setColumnValue(java.lang.Object, java.lang.Object, int)
*/
@Override
public ETableRecord setColumnValue(ETableRecord row, Object newValue, int column) {
row.set(column, newValue);
return row;
}
}
|
package pointGroups.gui;
import java.util.Collection;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.LinkedBlockingQueue;
import pointGroups.geometry.Point;
import pointGroups.geometry.Point3D;
import pointGroups.geometry.Point4D;
import pointGroups.geometry.Schlegel;
import pointGroups.geometry.Symmetry;
import pointGroups.gui.event.EventDispatcher;
import pointGroups.gui.event.types.RunEvent;
import pointGroups.gui.event.types.RunHandler;
import pointGroups.gui.event.types.SchlegelResultEvent;
import pointGroups.gui.event.types.Symmetry3DChooseEvent;
import pointGroups.gui.event.types.Symmetry3DChooseHandler;
import pointGroups.gui.event.types.Symmetry4DChooseEvent;
import pointGroups.gui.event.types.Symmetry4DChooseHandler;
import pointGroups.util.ExternalCalculationWrapper;
import pointGroups.util.polymake.SchlegelTransformer;
import pointGroups.util.polymake.wrapper.PolymakeWrapper;
/**
* Coordination object in the gui that listens to certain events that contribute
* to the next calculation. If a {@link RunEvent} is received, a calculation
* request will be sent to the {@link PolymakeWrapper}. Finally, for each
* calculation request, a {@link SchlegelResultEvent} that contains the request
* is fired.
*
* @author Alex
*/
public class PolymakeHub
implements Symmetry3DChooseHandler, Symmetry4DChooseHandler, RunHandler
{
protected final EventDispatcher dispatcher = EventDispatcher.get();
protected final ExternalCalculationWrapper pmWrapper;
private final BlockingQueue<Schlegel> buf = new LinkedBlockingQueue<>();
private final ResultProducer resProducer = new ResultProducer();
private final ResultConsumer resConsumer = new ResultConsumer();
private Symmetry<Point3D, ?> last3DSymmetry;
private Symmetry<Point4D, ?> last4DSymmetry;
private String lastSubgroup;
public PolymakeHub(final ExternalCalculationWrapper wrapper) {
this.pmWrapper = wrapper;
this.pmWrapper.start();
this.resConsumer.start();
this.resProducer.start();
dispatcher.addHandler(Symmetry3DChooseHandler.class, this);
dispatcher.addHandler(Symmetry4DChooseHandler.class, this);
dispatcher.addHandler(RunHandler.class, this);
}
@Override
public void onRunEvent(final RunEvent event) {
final int dimension = event.getDimension();
final double[] coords = event.getCoordinates();
Collection<? extends Point> images = null;
if (dimension == 3) {
if (last3DSymmetry != null) {
Point3D p = new Point3D(coords[0], coords[1], coords[2]);
images = last3DSymmetry.images(p, lastSubgroup);
}
}
else if (dimension == 4) {
if (last4DSymmetry != null) {
Point4D p = new Point4D(coords[0], coords[1], coords[2], coords[3]);
images = last4DSymmetry.images(p, lastSubgroup);
}
}
if (images != null) {
SchlegelTransformer st = new SchlegelTransformer(images);
pmWrapper.sendRequest(st);
resProducer.submit(st);
// dispatcher.fireEvent(new SchlegelResultEvent(st));
}
}
@Override
public void onSymmetry4DChooseEvent(final Symmetry4DChooseEvent event) {
this.last4DSymmetry = event.getSymmetry4D();
this.lastSubgroup = event.getSubgroup();
}
@Override
public void onSymmetry3DChooseEvent(final Symmetry3DChooseEvent event) {
this.last3DSymmetry = event.getSymmetry3D();
this.lastSubgroup = event.getSubgroup();
}
public Symmetry<Point3D, ?> getLast3DSymmetry() {
return this.last3DSymmetry;
}
public Symmetry<Point4D, ?> getLast4DSymmetry() {
return this.last4DSymmetry;
}
protected class ResultProducer
extends Thread
{
private final BlockingQueue<SchlegelTransformer> pending =
new LinkedBlockingQueue<>();
protected void submit(final SchlegelTransformer st) {
this.pending.add(st);
}
@Override
public void run() {
// TODO: Termination
SchlegelTransformer st;
while (true) {
try {
st = pending.take();
buf.add(st.get());
}
catch (InterruptedException e) {
// Handle termination
}
catch (ExecutionException e) {
e.printStackTrace();
}
}
}
}
protected class ResultConsumer
extends Thread
{
@Override
public void run() {
// TODO: Termination
while (true) {
try {
dispatcher.fireEvent(new SchlegelResultEvent(buf.take()));
}
catch (InterruptedException e) {
// TODO: Termination
}
}
}
}
}
|
package pw.agiledev.e2e;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.DateUtil;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import pw.agiledev.e2e.annotation.ExcelEntity;
import pw.agiledev.e2e.annotation.ExcelProperty;
import pw.agiledev.e2e.exception.ExcelParseException;
import pw.agiledev.e2e.extension.ExcelType;
/**
* EXCEL
*
* readExcel
* <code>
* ExcelHelper eh = ExcelHelper.readExcel("excel");
* </code>
* Excel
* <code>eh.getHeaders()</code>
* Excel
* <code>eh.getDatas()</code>
* Excel
*
* <code>eh.toEntitys(.class)</code>
* @ExcelEntity
* @ExcelProperty
*
* @author
* 2013-11-28 10:20:53
*/
public class ExcelHelper {
final public static int MIN_ROW_COLUMN_COUNT = 4;
private int lastColumnIndex = 4;
private String [] headers = null;
private String [][] datas = null;
private ExcelHelper(){}
@SuppressWarnings("rawtypes")
private static List<Class<? extends ExcelType>>
userDefinedType = new ArrayList<Class<? extends ExcelType>>();
/**
*
*
* ExcelType
* @author
* 2013-11-28 9:06:41
* @throws ExcelParseException
*/
public static void registerNewType(@SuppressWarnings("rawtypes") Class<? extends ExcelType> type)
throws ExcelParseException{
if(!userDefinedType.contains(type)){
userDefinedType.add(type);
}
}
/**
* Excel
*
* @author
* 2013-11-28 4:18:32
*/
public static ExcelHelper readExcel(String excelFilename) throws InvalidFormatException, IOException{
return readExcel(excelFilename, 0);
}
/**
* Excel
*
* @author
* 2013-11-28 3:40:05
*/
public static ExcelHelper readExcel(String excelFilename, int sheetIndex) throws InvalidFormatException, IOException{
return readExcel(new File(excelFilename), sheetIndex);
}
/**
* Excel
*
* @author
* 2013-11-28 3:40:05
*/
public static ExcelHelper readExcel(File file) throws InvalidFormatException, IOException{
return readExcel(file, 0);
}
/**
* Excel
*
* @author
* 2013-11-28 3:40:05
*/
public static ExcelHelper readExcel(File file, int sheetIndex) throws InvalidFormatException, IOException{
// Excel
Workbook wb = WorkbookFactory.create(file);
return _readExcel(wb, sheetIndex);
}
/**
* Excel
* @param ins
* @return
* @throws InvalidFormatException
* @throws IOException
*/
public static ExcelHelper readExcel(InputStream ins) throws InvalidFormatException, IOException{
return readExcel(ins, 0);
}
/**
* Excel
* @param ins
* @param sheetIndex
* @return
* @throws InvalidFormatException
* @throws IOException
*/
public static ExcelHelper readExcel(InputStream ins, int sheetIndex) throws InvalidFormatException, IOException{
return _readExcel(WorkbookFactory.create(ins), sheetIndex);
}
/**
*
*
* @author
* 2013-11-28 4:25:23
*/
public String [][] getDatas(){
return datas;
}
/**
*
*
* @author
* 2013-11-28 4:25:41
*/
public String [] getHeaders(){
return headers;
}
/**
*
*
* @author
* 2013-11-28 4:34:48
* @throws ExcelParseException
*/
public <T> List<T> toEntitys(Class<T> classType) throws ExcelParseException{
// @ExcelEntity
ExcelEntity excelEntity = classType.getAnnotation(ExcelEntity.class);
if(excelEntity == null){
throw new ExcelParseException("@ExcelEntity!");
}
// Excel
List<ExcelEntityField> eefs = _getEntityFields(classType);
List<T> entitys = new ArrayList<T>();
try {
for(String [] data : datas){
T obj = classType.newInstance();
for(ExcelEntityField eef : eefs){
Method method = obj.getClass().getDeclaredMethod("set" +
_toCapitalizeCamelCase(eef.getField().getName()),
eef.getField().getType());
try{
System.out.println(_getFieldValue(data[eef.getIndex()], eef.getField()));
method.invoke(obj, _getFieldValue(data[eef.getIndex()], eef.getField()));
}catch(Exception e){
if(eef.isRequired()){
throw new ExcelParseException("" + eef.getFieldName() + "!", e);
}
continue;
}
}
entitys.add(obj);
}
} catch (Exception e) {
throw new ExcelParseException(e);
}
return entitys;
}
/**
*
*
* @author
* 2013-11-28 8:03:35
*/
private String _toCapitalizeCamelCase(String name) {
if (name == null) {
return null;
}
//name = name.toLowerCase();
StringBuilder sb = new StringBuilder(name.length());
boolean upperCase = false;
for (int i = 0; i < name.length(); i++) {
char c = name.charAt(i);
if (c == '_') {
upperCase = true;
} else if (upperCase) {
sb.append(Character.toUpperCase(c));
upperCase = false;
} else {
sb.append(c);
}
}
name = sb.toString();
return name.substring(0, 1).toUpperCase() + name.substring(1);
}
/**
* Excel
*
* @author
* 2013-11-28 7:55:05
*/
private <T> List<ExcelEntityField> _getEntityFields(Class<T> classType) throws ExcelParseException {
List<ExcelEntityField> eefs = new ArrayList<ExcelHelper.ExcelEntityField>();
Field[] allFields = classType.getDeclaredFields();
for(Field field: allFields){
ExcelProperty excelProperty = field.getAnnotation(ExcelProperty.class);
// @ExcelProperty
if(excelProperty == null){
continue;
}
ExcelEntityField eef = new ExcelEntityField();
String key = excelProperty.value().trim();// Excel Header
boolean required = excelProperty.required();
int index = _indexOfHeader(key);
if(required && index == -1){
throw new ExcelParseException("" + key + "!");
}
eef.setField(field);
eef.setFieldName(key);
eef.setRequired(required);
eef.setIndex(_indexOfHeader(key));
eefs.add(eef);
}
return eefs;
}
/**
*
*
* value
* field
* @author
* 2013-11-28 7:55:35
*/
@SuppressWarnings("rawtypes")
private Object _getFieldValue(String value, Field field) throws ExcelParseException {
Class<?> type = field.getType();
String typeName = type.getName();
if("java.lang.String".equals(typeName)){
return value;
}
if("java.lang.Long".equals(typeName) || "long".equals(typeName)){
return Long.parseLong(value);
}
if("java.lang.Integer".equals(typeName) || "int".equals(typeName)){
return Integer.parseInt(value);
}
if("java.lang.Short".equals(typeName) || "short".equals(typeName)){
return Short.parseShort(value);
}
// Date
if("java.util.Date".equals(typeName)){
try {
return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(value);
} catch (ParseException e) {
throw new ExcelParseException("!");
}
}
// Timestamp
if("java.sql.Timestamp".equals(typeName)){
try {
return new Timestamp(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(value).getTime());
} catch (ParseException e) {
throw new ExcelParseException("!");
}
}
// Char
if("java.lang.Character".equals(typeName) || "char".equals(typeName)){
if(value.length() == 1){
return value.charAt(0);
}
}
for(Class<? extends ExcelType> et : userDefinedType){
if(et.getName().equals(typeName)){
try {
ExcelType newInstance = et.newInstance();
return newInstance.parseValue(value);
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
}
throw new ExcelParseException(" " + typeName + " !" );
}
/**
*
*
* @author
* 2013-11-28 7:57:01
*/
private int _indexOfHeader(String columnName){
for(int i = 0; i < headers.length; i ++){
if(headers[i].equals(columnName)){
return i;
}
}
return -1;
}
/**
* EXCEL
*
* @author
* 2013-11-28 3:47:38
*/
private void _parseExcelHeader(Row row) {
lastColumnIndex = Math.max(row.getLastCellNum(),MIN_ROW_COLUMN_COUNT);
headers = new String [lastColumnIndex];
// headers
for(int columnIndex = 0; columnIndex < lastColumnIndex; columnIndex ++){
Cell cell = row.getCell(columnIndex, Row.RETURN_BLANK_AS_NULL);
headers[columnIndex] = _getCellValue(cell).trim();
}
}
/**
* EXCEL
*
* @author
* 2013-11-28 3:47:27
*/
private void _parseExcelData(Sheet sheet, int rowStart, int rowEnd) {
datas = new String [rowEnd][lastColumnIndex];
for(int rowIndex = rowStart; rowIndex <= rowEnd; rowIndex ++ ){
Row row = sheet.getRow(rowIndex);
int rowNumber = rowIndex - rowStart;
for(int columnIndex = 0;columnIndex < lastColumnIndex; columnIndex ++){
Cell cell = row.getCell(columnIndex, Row.RETURN_BLANK_AS_NULL);
String value = _getCellValue(cell).trim();
datas[rowNumber][columnIndex] = value;
}
}
}
/**
*
*
* @author
* 2013-11-28 3:27:43
*/
private String _getCellValue(Cell cell) {
if(cell == null){
return "";
}
String value = "";
switch (cell.getCellType()) {
case Cell.CELL_TYPE_STRING:
value = cell.getRichStringCellValue().getString();
break;
case Cell.CELL_TYPE_NUMERIC:
if (DateUtil.isCellDateFormatted(cell)){
value = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(cell.getDateCellValue());
}else{
value = (long)cell.getNumericCellValue() + "";
}
break;
case Cell.CELL_TYPE_BOOLEAN:
value = cell.getBooleanCellValue() ? "TRUE" : "FALSE";
break;
case Cell.CELL_TYPE_FORMULA:
value = cell.getCellFormula();
break;
default:
}
return value;
}
/**
* Excel
* @param wb
* @param sheetIndex
* @return
*/
private static ExcelHelper _readExcel(Workbook wb, int sheetIndex){
ExcelHelper eh = new ExcelHelper();
// Excel Sheet
if(sheetIndex > wb.getNumberOfSheets()){
return null;
}
Sheet sheet = wb.getSheetAt(sheetIndex);
int rowStart = sheet.getFirstRowNum();
int rowEnd = sheet.getLastRowNum();
// EXCEL
eh._parseExcelHeader(sheet.getRow(0));
// EXCEL
eh._parseExcelData(sheet, rowStart + 1, rowEnd );
return eh;
}
/**
* Excel
*
* @author
* 2013-11-28 7:56:37
*/
private class ExcelEntityField{
private String fieldName;
private boolean required;
private Field field;
private int index;
public int getIndex() {
return index;
}
public void setIndex(int index) {
this.index = index;
}
public String getFieldName() {
return fieldName;
}
public void setFieldName(String fieldName) {
this.fieldName = fieldName;
}
public boolean isRequired() {
return required;
}
public void setRequired(boolean required) {
this.required = required;
}
public Field getField() {
return field;
}
public void setField(Field field) {
this.field = field;
}
}
}
|
package technology.tabula;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
@SuppressWarnings("serial")
public class TextChunk extends RectangularTextContainer<TextElement> implements HasText {
public static final TextChunk EMPTY = new TextChunk(0,0,0,0);
List<TextElement> textElements = new ArrayList<TextElement>();
public TextChunk(float top, float left, float width, float height) {
super(top, left, width, height);
}
public TextChunk(TextElement textElement) {
super(textElement.y, textElement.x, textElement.width, textElement.height);
this.add(textElement);
}
public TextChunk(List<TextElement> textElements) {
this(textElements.get(0));
for (int i = 1; i < textElements.size(); i++) {
this.add(textElements.get(i));
}
}
public TextChunk merge(TextChunk other) {
super.merge(other);
return this;
}
public void add(TextElement textElement) {
this.textElements.add(textElement);
this.merge(textElement);
}
public void add(List<TextElement> textElements) {
for (TextElement te: textElements) {
this.add(te);
}
}
public List<TextElement> getTextElements() {
return textElements;
}
public String getText() {
if (this.textElements.size() == 0) {
return "";
}
StringBuilder sb = new StringBuilder();
for (TextElement te: this.textElements) {
sb.append(te.getText());
}
return sb.toString();
}
@Override
public String getText(boolean useLineReturns) {
// TODO Auto-generated method stub
return null;
}
/**
* @return true if text contained in this TextChunk is the same repeated character
*/
public boolean isSameChar(Character c) {
return isSameChar(new Character[] { c });
}
public boolean isSameChar(Character[] c) {
String s = this.getText();
List<Character> chars = Arrays.asList(c);
for (int i = 0; i < s.length(); i++) {
if (!chars.contains(s.charAt(i))) { return false; }
}
return true;
}
/** Splits a TextChunk in two, at the position of the i-th TextElement
* @param textChunk the TextChunk to split
* @param i
* @return Two TextChunks, contained in a TextChunk[]
*/
public TextChunk[] splitAt(int i) {
if (i < 1 || i >= this.getTextElements().size()) {
throw new IllegalArgumentException();
}
TextChunk[] rv = new TextChunk[] {
new TextChunk(this.getTextElements().subList(0, i)),
new TextChunk(this.getTextElements().subList(i, this.getTextElements().size()))
};
return rv;
}
/**
* Removes runs of identical TextElements in this TextChunk
* For example, if the TextChunk contains this string of characters: "1234xxxxx56xx"
* and c == 'x' and minRunLength == 4, this method will return a list of TextChunk
* such that: ["1234", "56xx"]
*
* @param c the Character to remove
* @param minRunLength minimum run length to consider.
* @return
*/
public List<TextChunk> squeeze(Character c, int minRunLength) {
Character currentChar, lastChar = null;
int subSequenceLength = 0, subSequenceStart = 0;
TextChunk[] t;
List<TextChunk> rv = new ArrayList<TextChunk>();
for (int i = 0; i < this.getTextElements().size(); i++) {
TextElement textElement = this.getTextElements().get(i);
currentChar = textElement.getText().charAt(0);
if (lastChar != null && currentChar.equals(c) && lastChar.equals(currentChar)) {
subSequenceLength++;
}
else {
if (((lastChar != null && !lastChar.equals(currentChar)) || i + 1 == this.getTextElements().size()) && subSequenceLength >= minRunLength) {
if (subSequenceStart == 0 && subSequenceLength < this.getTextElements().size() - 1) {
t = this.splitAt(subSequenceLength);
}
else {
t = this.splitAt(subSequenceStart);
rv.add(t[0]);
}
rv.addAll(t[1].squeeze(c, minRunLength)); // Lo and behold, recursion.
break;
}
subSequenceLength = 1;
subSequenceStart = i;
}
lastChar = currentChar;
}
if (rv.isEmpty()) { // no splits occurred, hence this.squeeze() == [this]
if (subSequenceLength >= minRunLength && subSequenceLength < this.textElements.size()) {
TextChunk[] chunks = this.splitAt(subSequenceStart);
rv.add(chunks[0]);
}
else {
rv.add(this);
}
}
return rv;
}
public static boolean allSameChar(List<TextChunk> textChunks) {
char first = textChunks.get(0).getText().charAt(0);
for (TextChunk tc: textChunks) {
if (!tc.isSameChar(first)) return false;
}
return true;
}
public static List<Line> groupByLines(List<TextChunk> textChunks) {
float bbwidth = Rectangle.boundingBoxOf(textChunks).width;
List<Line> lines = new ArrayList<Line>();
Line l = new Line();
l.addTextChunk(textChunks.get(0));
textChunks.remove(0);
lines.add(l);
Line last = lines.get(lines.size() - 1);
for (TextChunk te: textChunks) {
if (last.horizontalOverlapRatio(te) < 0.1) {
if (last.width / bbwidth > 0.9 && TextChunk.allSameChar(last.getTextElements())) {
lines.remove(lines.size() - 1);
}
lines.add(new Line());
last = lines.get(lines.size() - 1);
}
last.addTextChunk(te);
}
if (last.width / bbwidth > 0.9 && TextChunk.allSameChar(last.getTextElements())) {
lines.remove(lines.size() - 1);
}
List<Line> rv = new ArrayList<Line>(lines.size());
for (Line line: lines) {
rv.add(Line.removeRepeatedCharacters(line, ' ', 3));
}
return rv;
}
}
|
package tigase.server;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Queue;
import java.util.Set;
import java.util.TreeMap;
import java.util.TreeSet;
import java.util.Timer;
import java.util.TimerTask;
import java.util.Collections;
import java.util.concurrent.CopyOnWriteArraySet;
import java.util.concurrent.ConcurrentSkipListMap;
import java.util.logging.Logger;
import java.util.logging.Level;
import tigase.xml.Element;
import tigase.util.JIDUtils;
import tigase.util.UpdatesChecker;
import tigase.xmpp.Authorization;
import tigase.xmpp.StanzaType;
import tigase.xmpp.PacketErrorTypeException;
import tigase.disco.XMPPService;
import tigase.disco.ServiceEntity;
import tigase.disco.ServiceIdentity;
import tigase.stats.StatRecord;
import tigase.stats.StatisticType;
import tigase.stats.StatisticsContainer;
import static tigase.server.MessageRouterConfig.*;
/**
* Class MessageRouter
*
*
* Created: Tue Nov 22 07:07:11 2005
*
* @author <a href="mailto:artur.hefczyc@tigase.org">Artur Hefczyc</a>
* @version $Rev$
*/
public class MessageRouter extends AbstractMessageReceiver {
// implements XMPPService {
public static final String INFO_XMLNS =
"http://jabber.org/protocol/disco#info";
public static final String ITEMS_XMLNS =
"http://jabber.org/protocol/disco#items";
private static final Logger log =
Logger.getLogger("tigase.server.MessageRouter");
private static final long startupTime = System.currentTimeMillis();
private Set<String> localAddresses = new CopyOnWriteArraySet<String>();
private String disco_name = DISCO_NAME_PROP_VAL;
private boolean disco_show_version = DISCO_SHOW_VERSION_PROP_VAL;
private ComponentRegistrator config = null;
private ServiceEntity serviceEntity = null;
private UpdatesChecker updates_checker = null;
private Map<String, XMPPService> xmppServices =
new ConcurrentSkipListMap<String, XMPPService>();
private Map<String, ServerComponent> components =
new ConcurrentSkipListMap<String, ServerComponent>();
private Map<String, ServerComponent> components_byId =
new ConcurrentSkipListMap<String, ServerComponent>();
private Map<String, ComponentRegistrator> registrators =
new ConcurrentSkipListMap<String, ComponentRegistrator>();
private Map<String, MessageReceiver> receivers =
new ConcurrentSkipListMap<String, MessageReceiver>();
public void processPacketMR(final Packet packet, final Queue<Packet> results) {
if (packet.getPermissions() != Permissions.ADMIN) {
try {
Packet res = Authorization.NOT_AUTHORIZED.getResponseMessage(packet,
"You are not authorized for this action.", true);
results.offer(res);
//processPacket(res);
} catch (PacketErrorTypeException e) {
log.warning("Packet processing exception: " + e);
}
return;
}
log.finest("Command received: " + packet.getStringData());
switch (packet.getCommand()) {
case OTHER:
if (packet.getStrCommand() != null) {
if (packet.getStrCommand().startsWith("controll/")) {
String[] spl = packet.getStrCommand().split("/");
String cmd = spl[1];
if (cmd.equals("stop")) {
Packet result = packet.commandResult("result");
results.offer(result);
//processPacket(result);
new Timer("Stopping...", true).schedule(new TimerTask() {
public void run() {
System.exit(0);
}
}, 2000);
}
}
}
break;
default:
break;
}
}
private ServerComponent getLocalComponent(String jid) {
ServerComponent comp = components_byId.get(jid);
if (comp != null) {
return comp;
}
String nick = JIDUtils.getNodeNick(jid);
if (nick == null) {
return null;
}
String host = JIDUtils.getNodeHost(jid);
comp = components.get(nick);
if (isLocalDomain(host)) {
return comp;
}
return null;
}
// private String isToLocalComponent(String jid) {
// String nick = JIDUtils.getNodeNick(jid);
// if (nick == null) {
// return null;
// String host = JIDUtils.getNodeHost(jid);
// if (isLocalDomain(host) && components.get(nick) != null) {
// return nick;
// return null;
private boolean isLocalDomain(String domain) {
return localAddresses.contains(domain);
}
public void processPacket(Packet packet) {
if (packet.getTo() == null) {
log.warning("Packet with TO attribute set to NULL: "
+ packet.getStringData());
return;
} // end of if (packet.getTo() == null)
// Intentionally comparing to static, final String
if (packet.getTo() == NULL_ROUTING) {
log.info("NULL routing, it is normal if server doesn't know how to"
+ " process packet: " + packet.toString());
try {
Packet error =
Authorization.FEATURE_NOT_IMPLEMENTED.getResponseMessage(packet,
"Feature not supported yet.", true);
addOutPacketNB(error);
} catch (PacketErrorTypeException e) {
log.warning("Packet processing exception: " + e);
}
return;
}
if (log.isLoggable(Level.FINER)) {
log.finer("Processing packet: " + packet.getElemName()
+ ", type: " + packet.getType());
}
if (log.isLoggable(Level.FINEST)) {
log.finest("Processing packet: " + packet.toString());
}
// Detect inifinite loop if from == to
// Maybe it is not needed anymore...
// There is a need to process packets with the same from and to address
// let't try to relax restriction and block all packets with error type
// 2008-06-16
if ((packet.getFrom() != null
&& packet.getFrom().equals(packet.getTo())
&& packet.getType() == StanzaType.error)
|| (packet.getFrom() == NULL_ROUTING
&& packet.getElemFrom() != null
&& packet.getElemFrom().equals(packet.getTo()))) {
log.warning("Possible infinite loop, dropping packet: "
+ packet.toString());
return;
}
ServerComponent comp = packet.getElemTo() == null ? null
: getLocalComponent(packet.getElemTo());
if (packet.isServiceDisco()
&& packet.getType() != null && packet.getType() == StanzaType.get
&& (comp != null || isLocalDomain(packet.getElemTo()))) {
log.finest("Processing disco query by: " + getComponentId());
Queue<Packet> results = new LinkedList<Packet>();
processDiscoQuery(packet, results);
if (results.size() > 0) {
for (Packet res: results) {
// No more recurrential calls!!
addOutPacketNB(res);
} // end of for ()
}
return;
}
String id = JIDUtils.getNodeID(packet.getTo());
String host = JIDUtils.getNodeHost(packet.getTo());
String nick = JIDUtils.getNodeNick(packet.getTo());
comp = getLocalComponent(id);
if (comp != null) {
log.finest("Packet is processing by: " + comp.getComponentId());
Queue<Packet> results = new LinkedList<Packet>();
if (comp == this) {
processPacketMR(packet, results);
} else {
comp.processPacket(packet, results);
}
if (results.size() > 0) {
for (Packet res: results) {
// No more recurrential calls!!
addOutPacketNB(res);
// processPacket(res);
} // end of for ()
}
return;
}
// Let's try to find message receiver quick way
// In case if packet is handled internally:
MessageReceiver first = null;
if (nick != null) {
first = receivers.get(nick);
} // end of if (nick != null)
if (first != null && host.equals(getDefHostName())) {
log.finest("Found receiver: " + first.getName());
first.addPacket(packet);
return;
} // end of if (mr != null)
// This packet is not processed localy, so let's find receiver
// which will send it to correct destination:
MessageReceiver s2s = null;
for (MessageReceiver mr: receivers.values()) {
Set<String> routings = mr.getRoutings();
if (routings != null) {
log.finest(mr.getName() + ": Looking for host: " + host +
" in " + routings.toString());
if (routings.contains(host) || routings.contains(id)) {
log.finest("Found receiver: " + mr.getName());
mr.addPacket(packet);
return;
} // end of if (routings.contains())
// Resolve wildchars routings....
if (mr.isInRegexRoutings(id)) {
log.finest("Found receiver: " + mr.getName());
mr.addPacket(packet);
return;
}
if (routings.contains("*")) {
// I found s2s receiver, remember it for later....
s2s = mr;
} // end of if (routings.contains())
} // end of if (routings != null)
else {
log.severe("Routings are null for: " + mr.getName());
} // end of if (routings != null) else
} // end of for (MessageReceiver mr: receivers.values())
// It is not for any local host, so maybe it is for some
// remote server, let's try sending it through s2s service:
if (localAddresses.contains(host) || comp != null) {
try {
addOutPacketNB(
Authorization.FEATURE_NOT_IMPLEMENTED.getResponseMessage(packet,
"Your request can not be processed.", true));
} catch (PacketErrorTypeException e) {
// This packet is to local domain, we don't want to send it out
// drop packet :-(
log.warning("Can't process packet to local domain, dropping..."
+ packet.toString());
}
return;
}
if (s2s != null) {
s2s.addPacket(packet);
} // end of if (s2s != null)
}
public void setConfig(ComponentRegistrator config) {
components.put(getName(), this);
this.config = config;
addRegistrator(config);
}
public void addRegistrator(ComponentRegistrator registr) {
log.info("Adding registrator: " + registr.getClass().getSimpleName());
registrators.put(registr.getName(), registr);
addComponent(registr);
for (ServerComponent comp : components.values()) {
// if (comp != registr) {
registr.addComponent(comp);
// } // end of if (comp != registr)
} // end of for (ServerComponent comp : components)
}
public void addRouter(MessageReceiver receiver) {
log.info("Adding receiver: " + receiver.getClass().getSimpleName());
addComponent(receiver);
receivers.put(receiver.getName(), receiver);
}
public void addComponent(ServerComponent component) {
log.info("Adding component: " + component.getClass().getSimpleName());
for (ComponentRegistrator registr : registrators.values()) {
if (registr != component) {
log.finer("Adding: " + component.getName() + " component to "
+ registr.getName() + " registrator.");
registr.addComponent(component);
} // end of if (reg != component)
} // end of for ()
components.put(component.getName(), component);
components_byId.put(component.getComponentId(), component);
if (component instanceof XMPPService) {
xmppServices.put(component.getName(), (XMPPService)component);
}
}
public Map<String, Object> getDefaults(Map<String, Object> params) {
Map<String, Object> defs = super.getDefaults(params);
MessageRouterConfig.getDefaults(defs, params, getName());
return defs;
}
private boolean inProperties = false;
public void setProperties(Map<String, Object> props) {
if (inProperties) {
return;
} else {
inProperties = true;
} // end of if (inProperties) else
disco_name = (String)props.get(DISCO_NAME_PROP_KEY);
disco_show_version = (Boolean)props.get(DISCO_SHOW_VERSION_PROP_KEY);
serviceEntity = new ServiceEntity("Tigase", "server", "Session manager");
serviceEntity.addIdentities(new ServiceIdentity[] {
new ServiceIdentity("server", "im", disco_name +
(disco_show_version ?
(" ver. " + tigase.server.XMPPServer.getImplementationVersion())
: ""))});
serviceEntity.addFeatures(XMPPService.DEF_FEATURES);
try {
super.setProperties(props);
String[] localAddresses = (String[])props.get(LOCAL_ADDRESSES_PROP_KEY);
this.localAddresses.clear();
if (localAddresses != null && localAddresses.length > 0) {
Collections.addAll(this.localAddresses, localAddresses);
this.localAddresses.add(getDefHostName());
}
Map<String, ComponentRegistrator> tmp_reg = registrators;
Map<String, MessageReceiver> tmp_rec = receivers;
components = new TreeMap<String, ServerComponent>();
registrators = new TreeMap<String, ComponentRegistrator>();
receivers = new TreeMap<String, MessageReceiver>();
setConfig(config);
MessageRouterConfig conf = new MessageRouterConfig(props);
String[] reg_names = conf.getRegistrNames();
for (String name: reg_names) {
ComponentRegistrator cr = tmp_reg.remove(name);
String cls_name =
(String)props.get(REGISTRATOR_PROP_KEY + name + ".class");
try {
if (cr == null || !cr.getClass().getName().equals(cls_name)) {
if (cr != null) {
cr.release();
}
cr = conf.getRegistrInstance(name);
cr.setName(name);
} // end of if (cr == null)
addRegistrator(cr);
} // end of try
catch (Exception e) {
e.printStackTrace();
} // end of try-catch
} // end of for (String name: reg_names)
for (ComponentRegistrator cr: tmp_reg.values()) {
cr.release();
} // end of for ()
tmp_reg.clear();
String[] msgrcv_names = conf.getMsgRcvNames();
for (String name: msgrcv_names) {
log.finer("Loading and registering message receiver: " + name);
MessageReceiver mr = tmp_rec.remove(name);
String cls_name =
(String)props.get(MSG_RECEIVERS_PROP_KEY + name + ".class");
try {
if (mr == null || !mr.getClass().getName().equals(cls_name)) {
if (mr != null) {
mr.release();
}
mr = conf.getMsgRcvInstance(name);
mr.setParent(this);
mr.setName(name);
mr.start();
} // end of if (cr == null)
addRouter(mr);
} // end of try
catch (Exception e) {
e.printStackTrace();
} // end of try-catch
} // end of for (String name: reg_names)
for (MessageReceiver mr: tmp_rec.values()) {
mr.release();
} // end of for ()
tmp_rec.clear();
if ((Boolean)props.get(UPDATES_CHECKING_PROP_KEY)) {
installUpdatesChecker((Long)props.get(UPDATES_CHECKING_INTERVAL_PROP_KEY));
} else {
stopUpdatesChecker();
}
} finally {
inProperties = false;
} // end of try-finally
}
private void stopUpdatesChecker() {
if (updates_checker != null) {
updates_checker.interrupt();
updates_checker = null;
}
}
private void installUpdatesChecker(long interval) {
stopUpdatesChecker();
updates_checker = new UpdatesChecker(interval, this,
"This is automated message generated by updates checking module.\n"
+ " You can disable this function changing configuration option: "
+ "'/" + getName() + "/" + UPDATES_CHECKING_PROP_KEY + "' or adjust"
+ " updates checking interval time changing option: "
+ "'/" + getName() + "/" + UPDATES_CHECKING_INTERVAL_PROP_KEY + "' which"
+ " now set to " + interval + " days.");
updates_checker.start();
}
private void processDiscoQuery(final Packet packet,
final Queue<Packet> results) {
String jid = packet.getElemTo();
String nick = JIDUtils.getNodeNick(jid);
String node = packet.getAttribute("/iq/query", "node");
Element query = packet.getElement().getChild("query").clone();
if (packet.isXMLNS("/iq/query", INFO_XMLNS)) {
if (isLocalDomain(jid)) {
query = getDiscoInfo(node, jid);
for (XMPPService comp: xmppServices.values()) {
List<Element> features = comp.getDiscoFeatures();
if (features != null) {
query.addChildren(features);
}
} // end of for ()
} else {
for (XMPPService comp: xmppServices.values()) {
// if (jid.startsWith(comp.getName() + ".")) {
Element resp = comp.getDiscoInfo(node, jid);
if (resp != null) {
query = resp;
break;
}
} // end of for ()
}
}
if (packet.isXMLNS("/iq/query", ITEMS_XMLNS)) {
boolean localDomain = isLocalDomain(jid);
for (XMPPService comp: xmppServices.values()) {
if (localDomain || (nick != null && comp.getName().equals(nick))) {
List<Element> items = comp.getDiscoItems(node, jid);
if (items != null && items.size() > 0) {
query.addChildren(items);
}
}
} // end of for ()
}
results.offer(packet.okResult(query, 0));
}
public Element getDiscoInfo(String node, String jid) {
Element query = serviceEntity.getDiscoInfo(null);
log.finest("Returing disco-info: " + query.toString());
return query;
}
public List<Element> getDiscoItems(String node, String jid) {
return null;
}
public List<StatRecord> getStatistics() {
List<StatRecord> stats = super.getStatistics();
long uptime = (System.currentTimeMillis() - startupTime);
long days = uptime / (24 * HOUR);
long hours = (uptime - (days * 24 * HOUR)) / HOUR;
long minutes = (uptime - (days * 24 * HOUR + hours * HOUR)) / MINUTE;
long seconds =
(uptime - (days * 24 * HOUR + hours * HOUR + minutes * MINUTE)) / SECOND;
// StringBuilder sb = new StringBuilder();
stats.add(new StatRecord(getName(), "Uptime", "time", ""
+ (days > 0 ? days + " day, " : "")
+ (hours > 0 ? hours + " hour, " : "")
+ (minutes > 0 ? minutes + " min, " : "")
+ (seconds > 0 ? seconds + " sec" : "")
, Level.INFO));
Runtime runtime = Runtime.getRuntime();
long maxMem = runtime.maxMemory();
long totalMem = runtime.totalMemory();
long freeMem = runtime.freeMemory();
stats.add(new StatRecord(getName(), "Max JVM mem", "long", maxMem,
Level.INFO));
stats.add(new StatRecord(getName(), "Total JVM mem", "long", totalMem,
Level.INFO));
stats.add(new StatRecord(getName(), "Free JVM mem", "long", freeMem,
Level.INFO));
return stats;
}
}
|
package tigase.server;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Queue;
import java.util.Set;
import java.util.TreeMap;
import java.util.TreeSet;
import java.util.Timer;
import java.util.TimerTask;
import java.util.Collections;
import java.util.concurrent.CopyOnWriteArraySet;
import java.util.concurrent.ConcurrentSkipListMap;
import java.util.logging.Logger;
import java.util.logging.Level;
import tigase.xml.Element;
import tigase.util.JIDUtils;
import tigase.xmpp.Authorization;
import tigase.xmpp.StanzaType;
import tigase.disco.XMPPService;
import tigase.disco.ServiceEntity;
import tigase.disco.ServiceIdentity;
import tigase.stats.StatRecord;
import tigase.stats.StatisticType;
import tigase.stats.StatisticsContainer;
import static tigase.server.MessageRouterConfig.*;
/**
* Class MessageRouter
*
*
* Created: Tue Nov 22 07:07:11 2005
*
* @author <a href="mailto:artur.hefczyc@tigase.org">Artur Hefczyc</a>
* @version $Rev$
*/
public class MessageRouter extends AbstractMessageReceiver {
// implements XMPPService {
public static final String INFO_XMLNS =
"http://jabber.org/protocol/disco#info";
public static final String ITEMS_XMLNS =
"http://jabber.org/protocol/disco#items";
private static final Logger log =
Logger.getLogger("tigase.server.MessageRouter");
private static final long startupTime = System.currentTimeMillis();
private String defHostName = null;
private static Set<String> localAddresses = new CopyOnWriteArraySet<String>();
private ComponentRegistrator config = null;
private ServiceEntity serviceEntity = null;
private Map<String, XMPPService> xmppServices =
new ConcurrentSkipListMap<String, XMPPService>();
private Map<String, ServerComponent> components =
new ConcurrentSkipListMap<String, ServerComponent>();
private Map<String, ComponentRegistrator> registrators =
new ConcurrentSkipListMap<String, ComponentRegistrator>();
private Map<String, MessageReceiver> receivers =
new ConcurrentSkipListMap<String, MessageReceiver>();
public void processPacket(final Packet packet, final Queue<Packet> results) {
String to = packet.getTo();
for (ServerComponent comp: components.values()) {
if (comp != this) {
comp.processPacket(packet, results);
} // end of if (comp != this)
} // end of for ()
// There is no better way to do it outside MessageRouter for now.
if (packet.isXMLNS("/iq/query", INFO_XMLNS)
|| packet.isXMLNS("/iq/query", ITEMS_XMLNS)
&& (packet.getType() != null && packet.getType() == StanzaType.get)) {
processDiscoQuery(packet, results);
}
// for (Packet res: results) {
// processPacket(res);
// } // end of for ()
if (!to.startsWith(getName())) {
// if (results.size() == 0) {
// Packet res =
// Authorization.FEATURE_NOT_IMPLEMENTED.getResponseMessage(packet,
// "Feature not supported yet.", true);
// processPacket(res);
// } // end of if (results.size() == null)
return;
}
if (packet.getPermissions() != Permissions.ADMIN) {
Packet res = Authorization.NOT_AUTHORIZED.getResponseMessage(packet,
"You are not authorized for this action.", true);
results.offer(res);
//processPacket(res);
return;
}
log.finest("Command received: " + packet.getStringData());
switch (packet.getCommand()) {
case OTHER:
if (packet.getStrCommand() != null) {
if (packet.getStrCommand().startsWith("controll/")) {
String[] spl = packet.getStrCommand().split("/");
String cmd = spl[1];
if (cmd.equals("stop")) {
Packet result = packet.commandResult("result");
results.offer(result);
//processPacket(result);
new Timer("Stopping...", true).schedule(new TimerTask() {
public void run() {
System.exit(0);
}
}, 2000);
}
}
}
break;
default:
break;
}
}
private String isToLocalComponent(String jid) {
for (String name: components.keySet()) {
for (String hostname: localAddresses) {
if (jid.equals(name + "." + hostname)) {
return name;
}
}
} // end of for ()
return null;
}
private boolean isLocalDomain(String domain) {
return localAddresses.contains(domain);
}
public void processPacket(Packet packet) {
if (packet.getTo() == null) {
log.warning("Packet with TO attribute set to NULL: "
+ packet.getStringData());
return;
} // end of if (packet.getTo() == null)
log.finer("Processing packet: " + packet.getElemName()
+ ", type: " + packet.getType());
log.finest("Processing packet: " + packet.getStringData()
+ ", to: " + packet.getTo()
+ ", from: " + packet.getFrom());
String local_comp_name = isToLocalComponent(packet.getTo());
if (localAddresses.contains(packet.getTo())
|| local_comp_name != null) {
// Detect inifinite loop if from == to
if (packet.getFrom() != null &&
packet.getFrom().equals(packet.getTo())) {
log.warning("Possible infinite loop, dropping packet: "
+ packet.toString());
return;
}
log.finest("This packet is addressed to server itself.");
Queue<Packet> results = new LinkedList<Packet>();
processPacket(packet, results);
if (results.size() > 0) {
for (Packet res: results) {
// No more recurrential calls!!
addOutPacketNB(res);
// processPacket(res);
} // end of for ()
return;
}
// // None of components wanted to process the packet, let's try
// // to insert it directly to component queue....
// MessageReceiver mr = receivers.get(local_comp_name);
// if (mr != null) {
// log.finest("Adding packet to local component: " + packet.toString());
// mr.addPacket(packet);
// return;
}
String host = JIDUtils.getNodeHost(packet.getTo());
String id = JIDUtils.getNodeID(packet.getTo());
String nick = JIDUtils.getNodeNick(packet.getTo());
// Let's try to find message receiver quick way
// In case if packet is handled internally:
MessageReceiver first = null;
if (nick != null) {
first = receivers.get(nick);
} // end of if (nick != null)
if (first != null) {
// Well, I found something. Now we need to make sure it is
// indeed to this receiver and it is not just accidental
// nick name match, so we are checking routing hosts.
Set<String> routings = first.getRoutings();
if (routings != null) {
log.finest(first.getName() + ": Looking for host: " + host
+ " in " + routings.toString());
if (routings.contains(host)) {
log.finest("Found receiver: " + first.getName());
first.addPacket(packet);
return;
} // end of if (routings.contains())
} // end of if (routings != null)
else {
log.severe("Routings are null for: " + first.getName());
} // end of if (routings != null) else
} // end of if (mr != null)
// This packet is not processed localy, so let's find receiver
// which will send it to correct destination:
MessageReceiver s2s = null;
for (MessageReceiver mr: receivers.values()) {
Set<String> routings = mr.getRoutings();
if (routings != null) {
log.finest(mr.getName() + ": Looking for host: " + host +
" in " + routings.toString());
if (routings.contains(host) || routings.contains(id)) {
log.finest("Found receiver: " + mr.getName());
mr.addPacket(packet);
return;
} // end of if (routings.contains())
// Resolve wildchars routings....
if (mr.isInRegexRoutings(id)) {
log.finest("Found receiver: " + mr.getName());
mr.addPacket(packet);
return;
}
if (routings.contains("*")) {
// I found s2s receiver, remember it for later....
s2s = mr;
} // end of if (routings.contains())
} // end of if (routings != null)
else {
log.severe("Routings are null for: " + mr.getName());
} // end of if (routings != null) else
} // end of for (MessageReceiver mr: receivers.values())
// It is not for any local host, so maybe it is for some
// remote server, let's try sending it through s2s service:
if (localAddresses.contains(JIDUtils.getNodeHost(packet.getTo()))
|| local_comp_name != null) {
if (packet.getType() == null || packet.getType() != StanzaType.error) {
// This packet is to local domain, we don't want to send it out
addOutPacketNB(
Authorization.FEATURE_NOT_IMPLEMENTED.getResponseMessage(packet,
"Your request can not be processed.", true));
} else {
// drop packet :-(
log.warning("Can't process packet to local domain, dropping..."
+ packet.toString());
}
return;
}
if (s2s != null) {
s2s.addPacket(packet);
} // end of if (s2s != null)
}
public void setConfig(ComponentRegistrator config) {
components.put(getName(), this);
this.config = config;
addRegistrator(config);
}
public void addRegistrator(ComponentRegistrator registr) {
log.info("Adding registrator: " + registr.getClass().getSimpleName());
registrators.put(registr.getName(), registr);
addComponent(registr);
for (ServerComponent comp : components.values()) {
// if (comp != registr) {
registr.addComponent(comp);
// } // end of if (comp != registr)
} // end of for (ServerComponent comp : components)
}
public void addRouter(MessageReceiver receiver) {
log.info("Adding receiver: " + receiver.getClass().getSimpleName());
addComponent(receiver);
receivers.put(receiver.getName(), receiver);
}
public void addComponent(ServerComponent component) {
log.info("Adding component: " + component.getClass().getSimpleName());
for (ComponentRegistrator registr : registrators.values()) {
if (registr != component) {
log.finer("Adding: " + component.getName() + " component to "
+ registr.getName() + " registrator.");
registr.addComponent(component);
} // end of if (reg != component)
} // end of for ()
components.put(component.getName(), component);
if (component instanceof XMPPService) {
xmppServices.put(component.getName(), (XMPPService)component);
}
}
public Map<String, Object> getDefaults(Map<String, Object> params) {
Map<String, Object> defs = super.getDefaults(params);
MessageRouterConfig.getDefaults(defs, params, getName());
return defs;
}
private boolean inProperties = false;
public void setProperties(Map<String, Object> props) {
if (inProperties) {
return;
} else {
inProperties = true;
} // end of if (inProperties) else
serviceEntity = new ServiceEntity("Tigase", "server", "Session manager");
serviceEntity.addIdentities(new ServiceIdentity[] {
new ServiceIdentity("server", "im", tigase.server.XMPPServer.NAME +
" ver. " + tigase.server.XMPPServer.getImplementationVersion())});
serviceEntity.addFeatures(XMPPService.DEF_FEATURES);
try {
super.setProperties(props);
String[] localAddresses = (String[])props.get(LOCAL_ADDRESSES_PROP_KEY);
this.localAddresses.clear();
if (localAddresses != null && localAddresses.length > 0) {
defHostName = localAddresses[0];
Collections.addAll(this.localAddresses, localAddresses);
} else {
defHostName = "localhost";
} // end of else
Map<String, ComponentRegistrator> tmp_reg = registrators;
Map<String, MessageReceiver> tmp_rec = receivers;
components = new TreeMap<String, ServerComponent>();
registrators = new TreeMap<String, ComponentRegistrator>();
receivers = new TreeMap<String, MessageReceiver>();
setConfig(config);
MessageRouterConfig conf = new MessageRouterConfig(props);
String[] reg_names = conf.getRegistrNames();
for (String name: reg_names) {
ComponentRegistrator cr = tmp_reg.remove(name);
String cls_name =
(String)props.get(REGISTRATOR_PROP_KEY + name + ".class");
try {
if (cr == null || !cr.getClass().getName().equals(cls_name)) {
if (cr != null) {
cr.release();
}
cr = conf.getRegistrInstance(name);
cr.setName(name);
} // end of if (cr == null)
addRegistrator(cr);
} // end of try
catch (Exception e) {
e.printStackTrace();
} // end of try-catch
} // end of for (String name: reg_names)
for (ComponentRegistrator cr: tmp_reg.values()) {
cr.release();
} // end of for ()
tmp_reg.clear();
String[] msgrcv_names = conf.getMsgRcvNames();
for (String name: msgrcv_names) {
log.finer("Loading and registering message receiver: " + name);
MessageReceiver mr = tmp_rec.remove(name);
String cls_name =
(String)props.get(MSG_RECEIVERS_PROP_KEY + name + ".class");
try {
if (mr == null || !mr.getClass().getName().equals(cls_name)) {
if (mr != null) {
mr.release();
}
mr = conf.getMsgRcvInstance(name);
mr.setParent(this);
mr.setName(name);
mr.start();
} // end of if (cr == null)
addRouter(mr);
} // end of try
catch (Exception e) {
e.printStackTrace();
} // end of try-catch
} // end of for (String name: reg_names)
for (MessageReceiver mr: tmp_rec.values()) {
mr.release();
} // end of for ()
tmp_rec.clear();
} finally {
inProperties = false;
} // end of try-finally
}
public String getDefHostName() {
return defHostName;
}
private void processDiscoQuery(final Packet packet,
final Queue<Packet> results) {
String jid = packet.getElemTo();
String node = packet.getAttribute("/iq/query", "node");
Element query = packet.getElement().getChild("query").clone();
if (packet.isXMLNS("/iq/query", INFO_XMLNS)) {
if (isLocalDomain(jid)) {
query = getDiscoInfo(node, jid);
for (XMPPService comp: xmppServices.values()) {
List<Element> features = comp.getDiscoFeatures();
if (features != null) {
query.addChildren(features);
}
} // end of for ()
} else {
for (XMPPService comp: xmppServices.values()) {
if (jid.startsWith(comp.getName() + ".")) {
Element resp = comp.getDiscoInfo(node, jid);
if (resp != null) {
query = resp;
break;
}
}
} // end of for ()
}
}
if (packet.isXMLNS("/iq/query", ITEMS_XMLNS)) {
boolean localDomain = isLocalDomain(jid);
for (XMPPService comp: xmppServices.values()) {
if (localDomain || jid.startsWith(comp.getName() + ".")) {
List<Element> items = comp.getDiscoItems(node, jid);
if (items != null && items.size() > 0) {
query.addChildren(items);
}
}
} // end of for ()
}
results.offer(packet.okResult(query, 0));
}
public Element getDiscoInfo(String node, String jid) {
Element query = serviceEntity.getDiscoInfo(null);
log.finest("Returing disco-info: " + query.toString());
return query;
}
public List<Element> getDiscoItems(String node, String jid) {
return null;
}
public List<StatRecord> getStatistics() {
List<StatRecord> stats = super.getStatistics();
long uptime = (System.currentTimeMillis() - startupTime);
long days = uptime / (24 * HOUR);
long hours = (uptime - (days * 24 * HOUR)) / HOUR;
long minutes = (uptime - (days * 24 * HOUR + hours * HOUR)) / MINUTE;
long seconds =
(uptime - (days * 24 * HOUR + hours * HOUR + minutes * MINUTE)) / SECOND;
// StringBuilder sb = new StringBuilder();
stats.add(new StatRecord(getName(), "Uptime", "time", ""
+ (days > 0 ? days + " day, " : "")
+ (hours > 0 ? hours + " hour, " : "")
+ (minutes > 0 ? minutes + " min, " : "")
+ (seconds > 0 ? seconds + " sec" : "")
, Level.INFO));
return stats;
}
}
|
package xyz.meunier.wav2pzx;
import xyz.meunier.wav2pzx.blockfinder.PZXBuilder;
import xyz.meunier.wav2pzx.blocks.PZXBlock;
import javax.sound.sampled.UnsupportedAudioFileException;
import java.io.BufferedOutputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
public class WAV2PZX {
private static boolean dumpPulses = false;
private enum EncodingVersion {
V10,
V20
}
private static final EncodingVersion version = EncodingVersion.V20;
/*
* Any durations are expressed in T cycles of standard 48k Spectrum CPU.
* This means one cycle equals 1/3500000 second.
*/
private static final float TARGET_HZ = (float) 3500000.0;
/**
* Main entry point for WAV2PZX. Two arguments are expected, first the
* source WAV filename and second the destination PZX file name.
*
* @param args program arguments, two are expected - the source WAV and the destination PZX file names
*/
public static void main(String[] args) {
if (args.length < 2) {
usage();
return;
}
final String fileIn = args[0];
final String pzxFileOut = args[1];
if (fileIn.isEmpty() || pzxFileOut.isEmpty()) {
usage();
return;
}
try {
// Read and convert the source WAV file from samples to a list of 0/1 pulses in units of TARGET_HZ
PulseList pulseList;
if (fileIn.toLowerCase().endsWith(".wav")) {
// Read and convert the source WAV file from samples to a list of 0/1 pulses in units of TARGET_HZ
pulseList = AudioFileTape.buildPulseList(fileIn, TARGET_HZ);
} else if (fileIn.toLowerCase().endsWith(".txt")) {
pulseList = TextFileTape.buildPulseList(fileIn);
} else {
usage();
return;
}
// Analyse the source data and translate into an equivalent list of PZX tape blocks
List<PZXBlock> pzxTape =
version == EncodingVersion.V20 ?
PZXBuilder.buildPZXTapeList(pulseList) :
LoaderContextImpl.buildPZXTapeList(pulseList);
if (dumpPulses) {
dumpPulses(pzxTape);
}
writePzxFile(pzxFileOut, pzxTape);
} catch (FileNotFoundException e) {
System.err.println("Error opening file " + fileIn + ": " + e.getMessage());
usage();
} catch (UnsupportedAudioFileException e) {
System.err.println("Unsupported audio file " + fileIn + ": " + e.getMessage());
Logger.getLogger(WAV2PZX.class.getName()).log(Level.FINE, e.toString(), e);
} catch (IOException e) {
System.err.println("Error with file " + fileIn + ": " + e.toString());
Logger.getLogger(WAV2PZX.class.getName()).log(Level.FINE, e.toString(), e);
}
}
private static void dumpPulses(List<PZXBlock> pzxTape) throws IOException {
try (OutputStream pulses = new BufferedOutputStream(Files.newOutputStream(Paths.get("pulseDump.txt")))) {
for (PZXBlock block : pzxTape) {
for (Long pulse : block.getPulses()) {
pulses.write(String.format("%d%n", pulse).getBytes());
}
}
}
}
private static void writePzxFile(String pzxFileOut, Iterable<PZXBlock> pzxTape) {
Path pzxFile = Paths.get(pzxFileOut);
// Overwrite the destination file with the extracted PZX data
try (OutputStream out = new BufferedOutputStream(Files.newOutputStream(pzxFile))) {
for (PZXBlock block : pzxTape) {
System.out.println(block.getSummary());
out.write(block.getPZXBlockDiskRepresentation());
}
} catch (IOException ex) {
System.err.println("Error writing file " + pzxFileOut + ": " + ex.getMessage());
Logger.getLogger(WAV2PZX.class.getName()).log(Level.FINE, ex.toString(), ex);
}
}
private static void usage() {
System.err.println("wav2pzx: usage: wav2pzx <infile.wav or txt> <outfile.pzx>");
}
}
|
package streams;
import java.util.*;
import java.util.stream.DoubleStream;
import java.util.stream.IntStream;
import java.util.stream.LongStream;
import java.util.stream.Stream;
import static java.util.Arrays.asList;
/**
*
* 3 primitive streams:
* - IntStream, specific functional interface IntSupplier
* - LongStream, specific functional interface LongSupplier
* - DoubleStream, specific functional interface DoubleSupplier
* they have additional and math operations: range, rangeClosed, max, min, average, sum and summaryStatistics
*
*/
public class PrimitiveStreams {
public static void main(String[] args) {
// Create IntStream
IntStream oneToNine1 = IntStream.range(1,10);
IntStream oneToNine2 = IntStream.iterate(1, x -> x + 1).limit(10);
LongStream oneToTen = LongStream.rangeClosed(1,10); // 1...10, end value inclusive
// Double stream
DoubleStream fractions = DoubleStream.iterate(10, d -> d / 2);
fractions.limit(3).forEach(System.out::println); // 10.0 5.0 2.5
// Converting Stream<Integer> to IntStream
List<Integer> ints = asList(1, 2, 3);
IntStream intStream1 = ints.stream().mapToInt(x -> x);
int sum = intStream1.sum();
// Stream<Object> to IntStream
Stream<String> objStream = Stream.of("lambda", "linq");
IntStream intStream2 = objStream.mapToInt(s -> s.length());
// Generate DoubleStream and convert to IntStream
IntStream randomNumbers = DoubleStream.generate(Math::random).mapToInt(x -> (int)(x * 100));
// randomNumbers.limit(3).forEach(System.out::println);
// Summarizing statics on stream (min, max, average, size and counts)
IntSummaryStatistics stats = intStream2.summaryStatistics();
if (stats.getCount() == 0)
throw new RuntimeException();
int deviation = stats.getMax() - stats.getMin();
// Handling optionals
// get method of each primitive Optional class are getAsInt, getAsLong and getAsDouble
// Below example illustrates diff between OptionalInt vs Optional<Integer>
IntStream odds = IntStream.iterate(11, x -> x + 2);
OptionalInt optFive = odds.filter(x -> x%5 == 0).findFirst();
System.out.println(optFive.getAsInt());
List<Integer> nums = asList(11, 21, 41, 35);
Optional<Integer> result = nums.stream().filter(i ->i % 7 == 0).findFirst();
System.out.println(result.get());
}
}
|
package org.jfree.chart.entity;
import java.awt.Shape;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import org.jfree.chart.HashUtilities;
import org.jfree.chart.title.Title;
import org.jfree.chart.util.ParamChecks;
import org.jfree.io.SerialUtilities;
import org.jfree.util.ObjectUtilities;
/**
* A class that captures information about a Title of a chart.
*
* @since 1.0.13
*/
public class TitleEntity extends ChartEntity {
/** For serialization. */
private static final long serialVersionUID = -4445994133561919083L;
//same as for ChartEntity!
/** The Title for the entity. */
private Title title;
/**
* Creates a new chart entity.
*
* @param area the area (<code>null</code> not permitted).
* @param title the title (<code>null</code> not permitted).
*/
public TitleEntity(Shape area, Title title) {
// defer argument checks...
this(area, title, null);
}
/**
* Creates a new chart entity.
*
* @param area the area (<code>null</code> not permitted).
* @param title the title (<code>null</code> not permitted).
* @param toolTipText the tool tip text (<code>null</code> permitted).
*/
public TitleEntity(Shape area, Title title, String toolTipText) {
// defer argument checks...
this(area, title, toolTipText, null);
}
/**
* Creates a new entity.
*
* @param area the area (<code>null</code> not permitted).
* @param title the title (<code>null</code> not permitted).
* @param toolTipText the tool tip text (<code>null</code> permitted).
* @param urlText the URL text for HTML image maps (<code>null</code>
* permitted).
*/
public TitleEntity(Shape area, Title title, String toolTipText,
String urlText) {
super(area, toolTipText, urlText);
ParamChecks.nullNotPermitted(title, "title");
this.title = title;
}
/**
* Returns the title that occupies the entity area.
*
* @return The title (never <code>null</code>).
*/
public Title getTitle() {
return this.title;
}
/**
* Returns a string representation of the chart entity, useful for
* debugging.
*
* @return A string.
*/
@Override
public String toString() {
StringBuilder sb = new StringBuilder("TitleEntity: ");
sb.append("tooltip = ");
sb.append(getToolTipText());
return sb.toString();
}
/**
* Tests the entity for equality with an arbitrary object.
*
* @param obj the object to test against (<code>null</code> permitted).
*
* @return A boolean.
*/
@Override
public boolean equals(Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof TitleEntity)) {
return false;
}
TitleEntity that = (TitleEntity) obj;
if (!getArea().equals(that.getArea())) {
return false;
}
if (!ObjectUtilities.equal(getToolTipText(), that.getToolTipText())) {
return false;
}
if (!ObjectUtilities.equal(getURLText(), that.getURLText())) {
return false;
}
if (!(this.title.equals(that.title))) {
return false;
}
return true;
}
/**
* Returns a hash code for this instance.
*
* @return A hash code.
*/
@Override
public int hashCode() {
int result = 41;
result = HashUtilities.hashCode(result, getToolTipText());
result = HashUtilities.hashCode(result, getURLText());
return result;
}
/**
* Returns a clone of the entity.
*
* @return A clone.
*
* @throws CloneNotSupportedException if there is a problem cloning the
* entity.
*/
@Override
public Object clone() throws CloneNotSupportedException {
return super.clone();
}
/**
* Provides serialization support.
*
* @param stream the output stream.
*
* @throws IOException if there is an I/O error.
*/
private void writeObject(ObjectOutputStream stream) throws IOException {
stream.defaultWriteObject();
SerialUtilities.writeShape(getArea(), stream);
}
/**
* Provides serialization support.
*
* @param stream the input stream.
*
* @throws IOException if there is an I/O error.
* @throws ClassNotFoundException if there is a classpath problem.
*/
private void readObject(ObjectInputStream stream)
throws IOException, ClassNotFoundException {
stream.defaultReadObject();
setArea(SerialUtilities.readShape(stream));
}
}
|
package IMP.Translate;
import AntlrGen.HMLParser;
import IMP.Basic.Template;
import IMP.HML2SMT;
import IMP.Infos.AbstractExpr;
import IMP.Scope.GlobalScope;
import IMP.Scope.Scope;
import IMP.Scope.Symbol;
import org.antlr.v4.runtime.ParserRuleContext;
import org.antlr.v4.runtime.tree.ParseTreeProperty;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Stack;
import org.antlr.v4.runtime.tree.ParseTree;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import IMP.Exceptions.TemplateNotDefinedException;
/**
* This is the visitor that does the main work for
* unrolling (translation) from HML model to SMT2 formulas
* @author fofo (fang.huixing@gmail.com)
*/
public class DynamicalVisitor extends HMLProgram2SMTVisitor {
private static Logger logger = LogManager.getLogger(DynamicalVisitor.class.getName());
private ParseTreeProperty<Scope> scopes;
private GlobalScope globals;
private Scope currentScope; // resolve symbols starting in this scope
private static boolean CHECKINGGUARD = false;
private int depth;
private HashMap<String, Template> tmpMap = new HashMap<String, Template>();
private VariableLink currentVariableLink;
private Stack<VariableLink> variableStack = new Stack<VariableLink>();
private VisitTree currentTree = new VisitTree(null, new DiscreteWithContinuous(), new ArrayList<Dynamic>());
public DynamicalVisitor(ParseTreeProperty<Scope> scopes, GlobalScope globals, HashMap<String, Template> tmpMap, int depth) {
super();
this.scopes = scopes;
this.globals = globals;
this.depth = depth;
this.tmpMap = tmpMap;
}
public Void visitHybridModel(HMLParser.HybridModelContext ctx) {
currentScope = globals;
visit(ctx.program());
return null;
}
public Void visitProgram(HMLParser.ProgramContext ctx) {
currentScope = scopes.get(ctx);
visit(ctx.blockStatement());
return null;
}
public Void visitSeqCom(HMLParser.SeqComContext ctx) {
for (HMLParser.BlockStatementContext bs : ctx.blockStatement())
visit(bs);
return null;
}
public Void visitConChoice(HMLParser.ConChoiceContext ctx) {
HMLParser.ExprContext condition = ctx.expr();
boolean condSatInit;
condSatInit = checkChoice(condition, currentTree);
if (condSatInit) {
//currentTree.addDiscrete(new ContextWithVarLink(condition, currentVariableLink));
visit(ctx.blockStatement(0));
}
else {
//currentTree.addDiscrete(new ContextWithVarLink(condition, currentVariableLink, true));
visit(ctx.blockStatement(1));
}
return null;
}
public Void visitAtomPro(HMLParser.AtomProContext ctx) {
visit(ctx.atom());
return null;
}
public Void visitAssignment(HMLParser.AssignmentContext ctx) {
currentTree.addDiscrete(new ContextWithVarLink(ctx, currentVariableLink));
return null;
}
/**
*
* @param ctx
* @return null
*/
public Void visitLoopPro(HMLParser.LoopProContext ctx) {
HMLParser.ExprContext boolCondition = ctx.parExpression().expr();
if (boolCondition instanceof HMLParser.ConstantTrueContext) {
while (!isMaxDepth()) {
visit(ctx.parStatement().blockStatement());
}
}
else if (boolCondition instanceof HMLParser.ConstantFalseContext) return null;
else {
HMLParser.ExprContext condition = ctx.parExpression().expr();
boolean condSatInit = checkChoice(condition, currentTree);
while (condSatInit && !isMaxDepth()) {
visit(ctx.parStatement().blockStatement());
if (isMaxDepth()) return null;
condSatInit = checkChoice(condition, currentTree);
}
}
return null;
}
public Void visitOde(HMLParser.OdeContext ctx) {
//maybe we don't have to check the guard initially
if (CHECKINGGUARD) {
boolean guardSatInit = checkGuard(ctx.guard(), currentTree);
if (guardSatInit) {
logger.debug("The Guard is satisfied initially, skip this flow.");
return null;
}
}
visit(ctx.equation());
if (currentTree.getCurrentDepth()>depth) return null;
currentTree.addContinuous(new ContextWithVarLink(ctx, currentVariableLink));
currentTree.getCurrentDynamics().setGuardCheckEnable(true);
currentTree.getCurrentDynamics().setDepth(currentTree.getCurrentDepth());
currentTree.addDynamics(currentTree.getCurrentDynamics());
currentTree.getCurrentDynamics().toString();
if (currentTree.getCurrentDepth() < depth+1) {
Dynamic dy = new DiscreteWithContinuous();
dy.addDiscrete(new ContextWithVarLink(ctx.guard(), currentVariableLink));
currentTree.setCurrentDynamics(dy);
}
else finishOnePath(currentTree);
return null;
}
private boolean checkGuard(HMLParser.GuardContext guard, VisitTree visitTree){
ParseTreeProperty<AbstractExpr> guardPtp = HML2SMT.getGuardPtp();
ConcreteExpr concreteExpr = new ConcreteExpr(guardPtp.get(guard));
return checkExpr(concreteExpr, visitTree);
}
private boolean checkChoice(HMLParser.ExprContext condition, VisitTree visitTree) {
while (condition instanceof HMLParser.ParExprContext) {
condition = ((HMLParser.ParExprContext) condition).parExpression().expr();
}
boolean needReverse = false;
while (condition instanceof HMLParser.NegationExprContext) {
condition = ((HMLParser.NegationExprContext) condition).expr();
needReverse = !needReverse;
}
ParseTreeProperty<AbstractExpr> exprs = HML2SMT.getExprPtp();
ConcreteExpr concreteExpr = new ConcreteExpr(exprs.get(condition));
// If the inner part is satisfied, we chose the right branch, so we do the negation (!)
boolean res = checkExpr(concreteExpr, visitTree);
if (needReverse) return !res;
else return res;
}
private boolean checkExpr(ConcreteExpr concreteExpr, VisitTree visitTree) {
Dynamic curDy = visitTree.getCurrentDynamics();
List<Dynamic> curDyList = visitTree.getCurrentDynamicList();
int curDepth = visitTree.getCurrentDepth();
curDy.setDepth(curDepth);
String conditionStr = curDy.getPartialResult(concreteExpr, currentVariableLink);
logger.debug("Condition: " + conditionStr);
return HML2SMT.checkTemporaryFormulas(this, conditionStr, curDepth);
}
private void finishOnePath(VisitTree leaf) {
//paths.add(leaf.getCurrentDynamicList());
//leaf.delete();//path
//System.out.println("Finish one Path" + paths.size());
}
public Void visitEqWithNoInit(HMLParser.EqWithNoInitContext ctx) {
return null;
}
public Void visitEqWithInit(HMLParser.EqWithInitContext ctx) {
currentTree.addDiscrete(new ContextWithVarLink(ctx, currentVariableLink));
return null;
}
public Void visitParaEq(HMLParser.ParaEqContext ctx) {
for (HMLParser.EquationContext e : ctx.equation()) visit(e);
return null;
}
public Void visitCallTem(HMLParser.CallTemContext ctx) {
StringBuilder key = new StringBuilder();
List<String> cvars = new ArrayList<String>(); // concrete vars
key.append(ctx.ID().getText());
if (ctx.exprList()!=null) {
List<HMLParser.ExprContext> exprs = ctx.exprList().expr();
for (HMLParser.ExprContext e : exprs) {
Symbol s = currentScope.resolve(e.getText());
cvars.add(e.getText());
key.append(getType(s.getType()));
}
Template template = tmpMap.get(key.toString());
if (template == null) {
String msg = "No template defined for " + ctx.getText();
logger.error(msg);
throw new TemplateNotDefinedException(msg);
}
List<String> fvars = template.getFormalVarNames(); //formal vars
variableStack.push(currentVariableLink);
VariableLink vlk = new VariableLink(currentVariableLink);
int i = 0;
for (String fv : fvars) {
vlk.setRealVar(fv, getRealVarName(cvars.get(i)));
i++;
}
currentVariableLink = vlk;
visit(template.getTemplateContext());
currentVariableLink = variableStack.pop();
}
return null;
}
public String getRealVarName(String virtualName) {
if (currentVariableLink==null) return virtualName;
return currentVariableLink.getRealVar(virtualName);
}
public Void visitTemplate(HMLParser.TemplateContext ctx) {
currentScope = scopes.get(ctx);
visit(ctx.parStatement().blockStatement());
return null;
}
public Void visitSendSignal(HMLParser.SendSignalContext ctx) {
logger.debug(String.format("Visit Send Signal %s -> %s ", ctx.getText(), currentVariableLink.getRealVar(ctx.signal().ID().getText())));
currentTree.addDiscrete(new ContextWithVarLink(ctx, currentVariableLink));
return null;
}
public Void visitSuspend(HMLParser.SuspendContext ctx) {
logger.debug("Visit Suspend " + ctx.getText());
try {
Integer time = Integer.valueOf(ctx.time.getText());
if (time<=0) return null;
}catch (NumberFormatException e) {
logger.info("Cannot transfer to integer for suspend time.");
}
commonContinuousAnalysis(ctx, ctx);
return null;
}
public Void visitWhenPro(HMLParser.WhenProContext ctx) {
commonContinuousAnalysis(ctx, ctx.guardedChoice());
return null;
}
/**
* Add continuous statements and its exit condition into dynamics objects
* @param ctx The parse rule context
* @param guard The exit condition
*/
private void commonContinuousAnalysis(ParserRuleContext ctx, ParserRuleContext guard){
currentTree.addContinuous(new ContextWithVarLink(ctx, currentVariableLink));
currentTree.getCurrentDynamics().setGuardCheckEnable(true);
currentTree.getCurrentDynamics().setDepth(currentTree.getCurrentDepth());
currentTree.addDynamics(currentTree.getCurrentDynamics());
currentTree.getCurrentDynamics().toString();
if (currentTree.getCurrentDepth() < depth+1) {
Dynamic dy = new DiscreteWithContinuous();
if (guard instanceof HMLParser.GuardedChoiceContext) {
List<HMLParser.SingleGuardedChoiceContext> gcList;
gcList = ((HMLParser.GuardedChoiceContext) guard).singleGuardedChoice();
if (gcList.size()==1) {
dy.addDiscrete(new ContextWithVarLink(gcList.get(0).guard(), currentVariableLink));
currentTree.setCurrentDynamics(dy);
visit(gcList.get(0).blockStatement());
return;
}
for (HMLParser.SingleGuardedChoiceContext sgc : gcList) {
boolean sat = checkGuard(sgc.guard(), currentTree);
if (sat) {
// if one of the guardedChoice is satisfiable
dy.addDiscrete(new ContextWithVarLink(sgc.guard(), currentVariableLink));
currentTree.setCurrentDynamics(dy);
visit(sgc.blockStatement());
return;
}
}
} else {
dy.addDiscrete(new ContextWithVarLink(guard, currentVariableLink));
currentTree.setCurrentDynamics(dy);
}
}
else finishOnePath(currentTree);
}
/**
* @param type inner type
* This method returns types in original model text,
* this enables correct variable linking
*/
public static String getType(Symbol.Type type) {
if (type.equals(Symbol.Type.Real)) return "float";
if (type.equals(Symbol.Type.Int)) return "int";
if (type.equals(Symbol.Type.Bool)) return "boolean";
if (type.equals(Symbol.Type.Signal)) return "Signal";
return "NULL";
}
public void setCurrentVariableLink(VariableLink currentVariableLink) {
this.currentVariableLink = currentVariableLink;
}
private boolean isMaxDepth(){
if (currentTree.getCurrentDepth()<depth+1) return false;
return true;
}
public Void visit(ParseTree tree){
if (isMaxDepth()) {
return null;
}
else return superVisit(tree);
}
public Void superVisit(ParseTree tree){
return super.superVisit(tree);
}
private List<Dynamic> copyList(List<Dynamic> from) {
List<Dynamic> l = new ArrayList<Dynamic>();
for (Dynamic s : from) {
l.add(s);
}
return l;
}
public List<List<Dynamic>> getPaths() {
List<List<Dynamic>> res = new ArrayList<List<Dynamic>>();
res.add(currentTree.getCurrentDynamicList());
return res;
}
}
|
import javax.naming.*;
public class DeployPoolDataSource {
public static void main(String[] args) {
String cpdsname;
String pathname;
if (args.length == 0)
{
cpdsname = "CPDS";
pathname = "c:\\temp";
}
else
{
if (args.length != 2)
{
System.out.println(
"Usage: RegisterCPDS <name of Datasource> <Name Registry location>");
return;
}
cpdsname = args[0];
pathname = args[1];
}
System.out.println(">>>Register DataSource " + cpdsname + " in " + pathname);
try {
System.setProperty(Context.INITIAL_CONTEXT_FACTORY,
"com.sun.jndi.fscontext.RefFSContextFactory");
System.setProperty(Context.PROVIDER_URL, "file:" + pathname);
registerDataSource(cpdsname, new InitialContext());
} catch (Exception e) {
System.out.println("Problem with registration");
e.printStackTrace();
return;
}
System.out.println(">>>Done Register");
}
private static void registerDataSource(String DSName, Context ctx)
{
// Create a UniJDBCConnectionPoolDataSource Object cpds and Set Its Properties
com.rs.u2.jdbcx.UniJDBCConnectionPoolDataSource cpds = new com.rs.u2.jdbcx.UniJDBCConnectionPoolDataSource();
cpds.setServerHost("localhost");
cpds.setAccount("HS.SALES");
cpds.setUser("username");
cpds.setPassword("password");
cpds.setUniJDBCCPMMaxConnections(-1);
cpds.setUniJDBCCPMInitPoolSize(0);
cpds.setUniJDBCCPMMinPoolSize(2);
cpds.setUniJDBCCPMMaxPoolSize(8);
cpds.setUniJDBCCPMServiceInterval(100);
cpds.setUniJDBCCPMMinAgeLimit(7200);
cpds.setUniJDBCCPMMinAgeLimit(3600);
// Register UniJDBCConnectionPoolDataSource Object with Naming Service That Uses JNDI API
try {
ctx.bind(DSName, cpds);
} catch (Exception e) {
System.out.println("Problem with registering the DataSource");
e.printStackTrace();
}
}
}
|
import java.util.ArrayList;
import org.junit.*;
import static org.junit.Assert.*;
public class DefinitionTest {
@Rule
public ClearRule clearRule = new ClearRule();
@Test
public void definition_instantiatesCorrectly_true() {
Definition testDefinition = new Definition("Sweaters for your feet");
assertEquals(true, testDefinition instanceof Definition);
}
@Test
public void getMeaning_returnsMeaning_true() {
Definition testDefinition = new Definition("Sweaters for your feet");
assertEquals("Sweaters for your feet", testDefinition.getMeaning());
}
@Test
public void getId_returnsDefinitionId_true() {
Definition testDefinition = new Definition("Sweaters for your feet");
assertTrue(Definition.all().size() == testDefinition.getId());
}
@Test
public void all_returnsAllInstancesOfDefinition_true() {
Definition testDefinitionOne = new Definition("Sweaters for your feet");
Definition testDefinitionTwo = new Definition("A piece of clothing that you wear on your feetsies");
assertTrue(Definition.all().contains(testDefinitionOne));
assertTrue(Definition.all().contains(testDefinitionTwo));
}
}
|
import java.util.ArrayList;
import org.junit.*;
import static org.junit.Assert.*;
public class DefinitionTest {
@Rule
public ClearRule clearRule = new ClearRule();
@Test
public void definition_instantiatesCorrectly_true() {
Definition testDefinition = new Definition("Sweaters for your feet");
assertEquals(true, testDefinition instanceof Definition);
}
@Test
public void getMeaning_returnsMeaning_true() {
Definition testDefinition = new Definition("Sweaters for your feet");
assertEquals("Sweaters for your feet", testDefinition.getMeaning());
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.