answer
stringlengths 17
10.2M
|
|---|
package org.ovirt.engine.core.common.businessentities;
import java.util.Map;
import org.ovirt.engine.core.common.AuditLogType;
import org.ovirt.engine.core.common.errors.VdcBllErrors;
import org.ovirt.engine.core.common.eventqueue.EventResult;
import org.ovirt.engine.core.compat.Guid;
import org.ovirt.engine.core.compat.TransactionScopeOption;
public interface IVdsEventListener {
void vdsNotResponding(VDS vds, boolean executeSshSoftFencing); // BLL
void vdsNonOperational(Guid vdsId, NonOperationalReason type, boolean logCommand, boolean saveToDb,
Guid domainId); // BLL
void vdsNonOperational(Guid vdsId, NonOperationalReason type, boolean logCommand, boolean saveToDb,
Guid domainId,
Map<String, String> customLogValues); // BLL
void vdsMovedToMaintenance(VDS vds); // BLL
EventResult storageDomainNotOperational(Guid storageDomainId, Guid storagePoolId); // BLL
EventResult masterDomainNotOperational(Guid storageDomainId, Guid storagePoolId, boolean isReconstructToInactiveDomains); // BLL
void processOnVmStop(Guid vmId);
boolean vdsUpEvent(VDS vds);
void processOnClientIpChange(VDS vds, Guid vmId);
void processOnCpuFlagsChange(Guid vdsId);
void processOnVmPoweringUp(Guid vds_id, Guid vmid, String display_ip, int display_port);
void handleVdsVersion(Guid vdsId);
void rerun(Guid vmId);
void runningSucceded(Guid vmId);
void removeAsyncRunningCommand(Guid vmId);
// void VdsNetworkConfigurationChanged(VDS vds);
void storagePoolUpEvent(StoragePool storagePool, boolean isNewSpm);
void storagePoolStatusChange(Guid storagePoolId, StoragePoolStatus status, AuditLogType auditLogType,
VdcBllErrors error);
void storagePoolStatusChange(Guid storagePoolId, StoragePoolStatus status, AuditLogType auditLogType,
VdcBllErrors error, TransactionScopeOption transactionScopeOption);
void storagePoolStatusChanged(Guid storagePoolId, StoragePoolStatus status);
void runFailedAutoStartVM(Guid vmId);
boolean restartVds(Guid vdsId);
}
|
package org.ovirt.engine.core.extensions.mgr;
import org.slf4j.Logger;
import org.ovirt.engine.api.extensions.Base;
import org.ovirt.engine.api.extensions.ExtMap;
import org.ovirt.engine.api.extensions.Extension;
public class ExtensionProxy implements Extension {
private Extension proxied;
private ExtMap context;
private void dumpMap(String prefix, ExtMap map) {
Logger logger = context.<Logger>get(ExtensionsManager.TRACE_LOG_CONTEXT_KEY);
if (logger.isDebugEnabled()) {
logger.debug(prefix + " BEGIN");
logger.debug(map.toString());
logger.debug(prefix + " END");
}
}
public ExtensionProxy(Extension proxied, ExtMap context) {
this.proxied = proxied;
this.context = context;
}
public Extension getExtension() {
return proxied;
}
public ExtMap getContext() {
return context;
}
@Override
public void invoke(ExtMap input, ExtMap output) {
input.putIfAbsent(Base.InvokeKeys.CONTEXT, context);
dumpMap("Invoke Input", input);
try {
proxied.invoke(input, output);
} catch (Throwable e) {
output.mput(
Base.InvokeKeys.RESULT,
Base.InvokeResult.FAILED
).mput(
Base.InvokeKeys.MESSAGE,
String.format(
"Exception: %s: %s",
e.getClass(),
e.getMessage()
)
).mput(
ExtensionsManager.CAUSE_OUTPUT_KEY,
e
);
}
dumpMap("Invoke Output", output);
}
public ExtMap invoke(ExtMap input, boolean allowUnsupported, boolean allowFail) {
ExtMap output = new ExtMap();
invoke(input, output);
String message = output.<String>get(Base.InvokeKeys.MESSAGE);
switch(output.<Integer>get(Base.InvokeKeys.RESULT, Base.InvokeResult.FAILED)) {
case Base.InvokeResult.SUCCESS:
break;
case Base.InvokeResult.UNSUPPORTED:
if (!allowUnsupported) {
throw new ExtensionInvokeCommandUnsupportedException(
message == null ? "Unsupported command" : message,
input,
output
);
}
break;
case Base.InvokeResult.FAILED:
default:
if (!allowFail) {
throw new ExtensionInvokeCommandFailedException(
message == null ? "Invoke failed" : message,
input,
output
);
}
break;
}
return output;
}
public ExtMap invoke(ExtMap input, boolean allowUnsupported) {
return invoke(input, allowUnsupported, false);
}
public ExtMap invoke(ExtMap input) {
return invoke(input, false, false);
}
}
|
package gov.nih.nci.cagrid.wsenum.utils;
import gov.nih.nci.cagrid.common.Utils;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.NoSuchElementException;
import javax.xml.namespace.QName;
import javax.xml.soap.SOAPElement;
import org.globus.ws.enumeration.EnumIterator;
import org.globus.ws.enumeration.IterationConstraints;
import org.globus.ws.enumeration.IterationResult;
import org.globus.ws.enumeration.TimeoutException;
import org.globus.wsrf.encoding.ObjectSerializer;
import org.globus.wsrf.encoding.SerializationException;
/**
* PersistantSDKObjectIterator
* Enumeration iterator which provides for persisting caCORE SDK objects to disk
*
* @author <A HREF="MAILTO:ervin@bmi.osu.edu">David W. Ervin</A>
*
* @created Aug 17, 2006
* @version $Id$
*/
public class SimplePersistantSDKObjectIterator implements EnumIterator {
private static StringBuffer configFileContents = null;
private File file = null;
private BufferedReader fileReader = null;
private QName objectQName = null;
private boolean isReleased;
private SimplePersistantSDKObjectIterator(File file, QName objectQName) throws FileNotFoundException {
this.file = file;
this.fileReader = new BufferedReader(new FileReader(file));
this.objectQName = objectQName;
this.isReleased = false;
}
/**
* Loads a wsdd config file for discovering type mappings needed to serialize / deserialize SDK objects
*
* @param filename
* @throws Exception
*/
public static void loadWsddConfig(String filename) throws Exception {
configFileContents = Utils.fileToStringBuffer(new File(filename));
}
/**
* Serializes a List of caCORE SDK generated objects to a temp file on
* the local disk, then creates an EnumIterator which can return
* those objects.
*
* @param objects
* The list of caCORE SDK objects to be enumerated
* @param objectQName
* The QName of the objects
* @return
* @throws Exception
*/
public static EnumIterator createIterator(List objects, QName objectQName) throws Exception {
return createIterator(objects, objectQName, File.createTempFile("EnumIteration", ".serialized").getAbsolutePath());
}
/**
* Serializes a List of caCORE SDK generated objects to a specified file on
* the local disk, then creates an EnumIterator which can return
* those objects.
*
* @param objects
* The list of caCORE SDK objects to be enumerated
* @param objectQName
* The QName of the objects
* @param filename
* The name of the file to serialize objects into
* @return
* @throws Exception
*/
public static EnumIterator createIterator(List objects, QName objectQName, String filename) throws Exception {
writeSdkObjects(objects, objectQName, filename);
return new SimplePersistantSDKObjectIterator(new File(filename), objectQName);
}
/**
* Writes the SDK serializable objects to disk
*
* @param objects
* The list of objects to write out
* @param name
* The QName of the objects
* @param filename
* The filename to store the objects into
* @throws Exception
*/
private static void writeSdkObjects(List objects, QName name, String filename) throws Exception {
BufferedWriter fileWriter = new BufferedWriter(new FileWriter(filename));
Iterator objIter = objects.iterator();
while (objIter.hasNext()) {
StringWriter writer = new StringWriter();
if (configFileContents != null) {
Utils.serializeObject(objIter.next(), name, writer,
new ByteArrayInputStream(configFileContents.toString().getBytes()));
} else {
Utils.serializeObject(objIter.next(), name, writer);
}
String xml = writer.toString().trim();
fileWriter.write(String.valueOf(xml.length()) + "\n");
fileWriter.write(xml);
}
fileWriter.flush();
fileWriter.close();
}
/**
* Retrieves the next set of items of the enumeration.
* <b>Note:</b> This implementation ignores any iteration constraints except for max elements
*
* @param constraints the constrains for this iteration. Can be null.
* If null, default constraints must be assumed.
* @return the result of this iteration that fulfils the specified
* constraints. It must always be non-null.
* @throws TimeoutException if <tt>maxTime</tt> constraint was specified
* and the enumeration data was not collected within that time.
* <i>This is never thrown in this implementation</i>
* @throws NoSuchElementException if iterator has no more elements
*/
public IterationResult next(IterationConstraints constraints) throws TimeoutException, NoSuchElementException {
// check for release
if (isReleased) {
throw new NoSuchElementException("Enumeration has been released");
}
// temporary list to hold SOAPElements
List soapElements = new ArrayList(constraints.getMaxElements());
// start building results
String xml = null;
while (soapElements.size() < constraints.getMaxElements() && (xml = getNextXmlChunk()) != null) {
try {
SOAPElement element = ObjectSerializer.toSOAPElement(xml, objectQName);
soapElements.add(element);
} catch (SerializationException ex) {
release();
NoSuchElementException nse = new NoSuchElementException("Error serializing element -- " + ex.getMessage());
nse.setStackTrace(ex.getStackTrace());
throw nse;
}
}
// if the xml text is null, we're at the end of the iteration
return wrapUpElements(soapElements, xml == null);
}
/**
* Encapsulates converting the list of SOAPElements to an array, then an Iteration Result
*
* @param soapElements
* @param end
* @return
*/
private IterationResult wrapUpElements(List soapElements, boolean end) {
SOAPElement[] elements = new SOAPElement[soapElements.size()];
soapElements.toArray(elements);
return new IterationResult(elements, end);
}
/**
* Reads the next chunk of XML from the file
*
* @return
* Null if no more XML is found
*/
private String getNextXmlChunk() {
try {
String charCountStr = fileReader.readLine();
if (charCountStr != null) {
int toRead = Integer.parseInt(charCountStr);
char[] charBuff = new char[toRead];
int count = 0;
int len = 0;
while (count < toRead) {
len = fileReader.read(charBuff, count, charBuff.length - count);
count += len;
}
return new String(charBuff);
} else {
return null;
}
} catch (IOException ex) {
ex.printStackTrace();
return null;
}
}
/**
* Releases the enumeration's resources. Specificaly, this deletes the underlying serialization file
*/
public void release() {
try {
fileReader.close();
} catch (Exception ex) {
ex.printStackTrace();
}
file.delete();
isReleased = true;
}
}
|
package de.rocketinternet.android.bucket.network;
import android.content.Context;
import android.net.Uri;
import com.squareup.okhttp.Cache;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import org.json.JSONException;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.Map;
import de.rocketinternet.android.bucket.RocketBucket;
import de.rocketinternet.android.bucket.models.Bucket;
import de.rocketinternet.android.bucket.models.Experiment;
/**
* @author Sameh Gerges
*/
public class NetworkTask implements com.squareup.okhttp.Callback {
private static String formSplitUrl(String endpoint, String deviceId) {
return endpoint + "?user_id=" + deviceId;
}
private final String HTTP_HEADER_API_KEYE = "X-Api-Key";
private final String DIR_NAME_CACHING = "rocket_bucket";
private final int CACHE_SIZE = 1 * 1024 * 1024; // 1 MiB
private final int MAX_RETRY_COUNT = 5;
private static OkHttpClient client;
private final Request request;
private final NetworkTaskCallback callBack;
private int trailsCount;
public NetworkTask(Context context, String apiKey, String url, NetworkTaskCallback callBack) {
this.callBack = callBack;
if (client == null) {
this.client = new OkHttpClient();
if (!RocketBucket.isDebug()) {//so we do not stuck with cached response while developing
File cachingDir = new File(context.getCacheDir(), DIR_NAME_CACHING);
if (cachingDir.exists() || cachingDir.mkdirs()) {
this.client.setCache(new Cache(cachingDir, CACHE_SIZE));
} else {
callBack.onFailure(new RuntimeException("RocketBucket: failed to create caching dir " + cachingDir.getAbsolutePath()));
}
}
/*if (RocketBucket.isDebug()) {
com.squareup.okhttp.logging.HttpLoggingInterceptor loggingInterceptor = new com.squareup.okhttp.logging.HttpLoggingInterceptor(new HttpLoggingInterceptor.Logger() {
@Override
public void log(String s) {
Log.d(RocketBucket.TAG, s);
}
});
loggingInterceptor.setLevel(com.squareup.okhttp.logging.HttpLoggingInterceptor.Level.BASIC);
this.client.networkInterceptors().add(loggingInterceptor);
}*/
}
this.request = new Request.Builder()
.url(url)
.header(HTTP_HEADER_API_KEYE, apiKey).build();
client.newCall(this.request).enqueue(this);
}
@Override
public void onFailure(Request request, IOException e) {
trailsCount++;
if (trailsCount < MAX_RETRY_COUNT) {
client.newCall(request).enqueue(this);
}
callBack.onFailure(e);
}
@Override
public void onResponse(com.squareup.okhttp.Response response) throws IOException {
if (response.body() != null && response.isSuccessful()) {
InputStream inputStream = null;
try {
inputStream = response.body().byteStream();
callBack.onSuccess(inputStream);
} catch (Throwable t) {
callBack.onFailure(t);
} finally {
if (inputStream != null) {
inputStream.close();
}
}
}
}
private interface NetworkTaskCallback {
void onSuccess(InputStream inputStream) throws IOException, JSONException;
void onFailure(Throwable t);
}
public interface Callback<T> {
void onCompletion(T response, Throwable error);
}
public static void updateLatestBucket(Context context, String endpoint, String apiKey, String deviceId, final Callback<Map<String, Bucket>>
experimentMap) {
new NetworkTask(context, apiKey, formSplitUrl(endpoint, deviceId), new NetworkTaskCallback() {
@Override
public void onSuccess(InputStream inputStream) throws IOException {
experimentMap.onCompletion(JsonParser.parseExperiments(inputStream), null);
}
@Override
public void onFailure(Throwable t) {
experimentMap.onCompletion(null, t);
}
});
}
public static void getAllBuckets(Context context, String endpoint, String apiKey, final Callback<List<Experiment>>
experimentMap) {
new NetworkTask(context, apiKey, buildAllBucketsEndUrl(endpoint), new
NetworkTaskCallback() {
@Override
public void onSuccess(InputStream inputStream) throws IOException, JSONException {
experimentMap.onCompletion(JsonParser.parseAllExperiments(inputStream), null);
}
@Override
public void onFailure(Throwable t) {
experimentMap.onCompletion(null, t);
}
});
}
private static String buildAllBucketsEndUrl(String endpoint) {
return Uri.parse(endpoint).buildUpon().appendPath("all").toString();
}
}
|
package io.cattle.platform.systemstack.service;
import static io.cattle.platform.core.model.tables.ProjectTemplateTable.*;
import io.cattle.platform.archaius.util.ArchaiusUtil;
import io.cattle.platform.async.utils.TimeoutException;
import io.cattle.platform.core.dao.GenericResourceDao;
import io.cattle.platform.core.model.ProjectTemplate;
import io.cattle.platform.lock.LockCallbackWithException;
import io.cattle.platform.lock.LockManager;
import io.cattle.platform.object.ObjectManager;
import io.cattle.platform.object.process.ObjectProcessManager;
import io.cattle.platform.systemstack.catalog.CatalogService;
import io.cattle.platform.systemstack.lock.ProjectTemplateLoadLock;
import io.cattle.platform.task.Task;
import io.cattle.platform.util.exception.ExceptionUtils;
import io.cattle.platform.util.type.InitializationTask;
import io.github.ibuildthecloud.gdapi.condition.Condition;
import io.github.ibuildthecloud.gdapi.condition.ConditionType;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import javax.inject.Inject;
import javax.inject.Named;
import org.apache.cloudstack.managed.context.NoExceptionRunnable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.netflix.config.DynamicBooleanProperty;
public class ProjectTemplateService implements InitializationTask, Task {
private static final DynamicBooleanProperty CATALOG_URL = ArchaiusUtil.getBoolean("catalog.url");
private static final DynamicBooleanProperty LAUNCH_CATALOG = ArchaiusUtil.getBoolean("catalog.execute");
private static final DynamicBooleanProperty DEFAULTS = ArchaiusUtil.getBoolean("project.template.defaults");
private static final Logger log = LoggerFactory.getLogger(ProjectTemplateService.class);
@Inject
CatalogService catalogService;
@Inject @Named("CoreExecutorService")
ExecutorService executor;
@Inject
ObjectManager objectManager;
@Inject
ObjectProcessManager processManager;
@Inject
GenericResourceDao resourceDao;
@Inject
LockManager lockManager;
boolean initialRun = true;
@Override
public void start() {
Runnable run = new NoExceptionRunnable() {
@Override
protected void doRun() throws Exception {
while (true) {
try {
reload();
log.info("Loaded project templates from the catalog");
break;
} catch (IOException e) {
}
Thread.sleep(1000);
}
}
};
CATALOG_URL.addCallback(run);
LAUNCH_CATALOG.addCallback(run);
DEFAULTS.addCallback(run);
executor.submit(run);
}
@Override
public void run() {
try {
reload();
} catch (IOException e) {
} catch (InterruptedException e) {
}
}
protected void reload() throws IOException, InterruptedException {
try {
lockManager.tryLock(new ProjectTemplateLoadLock(), new LockCallbackWithException<Object, Exception>() {
@Override
public Object doWithLock() throws Exception {
reloadWithLock();
return null;
}
}, Exception.class);
} catch (Exception e) {
ExceptionUtils.rethrow(e, InterruptedException.class);
ExceptionUtils.rethrow(e, IOException.class);
ExceptionUtils.rethrowRuntime(e);
}
}
protected void reloadWithLock() throws IOException, InterruptedException {
if (!LAUNCH_CATALOG.get() || !DEFAULTS.get()) {
return;
}
List<ProjectTemplate> installedTemplates = objectManager.find(ProjectTemplate.class,
PROJECT_TEMPLATE.IS_PUBLIC, true,
PROJECT_TEMPLATE.REMOVED, null,
PROJECT_TEMPLATE.EXTERNAL_ID, new Condition(ConditionType.LIKE, "catalog:
Map<String, Map<Object, Object>> templatesToInstall = catalogService.getTemplates(installedTemplates);
int i = 0;
while (initialRun && templatesToInstall.size() == 0) {
log.info("Waiting for project templates to load");
if (i++ > 120) {
throw new TimeoutException("Waiting for project templates");
}
Thread.sleep(2000);
templatesToInstall = catalogService.getTemplates(installedTemplates);
}
for (ProjectTemplate installed : installedTemplates) {
templatesToInstall.remove(installed.getExternalId());
}
for (Map.Entry<String, Map<Object, Object>> entry : templatesToInstall.entrySet()) {
Map<Object, Object> toInstall = entry.getValue();
toInstall.put(PROJECT_TEMPLATE.ACCOUNT_ID, null);
toInstall.put(PROJECT_TEMPLATE.IS_PUBLIC, true);
toInstall.put(PROJECT_TEMPLATE.EXTERNAL_ID, entry.getKey());
log.info("Adding project template [{}]", entry.getKey());
Map<String, Object> data = objectManager.convertToPropertiesFor(ProjectTemplate.class, toInstall);
resourceDao.createAndSchedule(ProjectTemplate.class, data);
}
initialRun = false;
}
@Override
public String getName() {
return "project.template.reload";
}
}
|
package org.openforis.collect.earth.app.service;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import javax.annotation.PostConstruct;
import org.apache.commons.dbcp.BasicDataSource;
import org.openforis.collect.earth.app.EarthConstants;
import org.openforis.collect.earth.core.utils.CsvReaderUtils;
import org.openforis.idm.metamodel.Schema;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;
import au.com.bytecode.opencsv.CSVReader;
@Component
public class RegionCalculationUtils {
private static final String SHRUB_COUNT = "shrub_count";
private static final String TREE_COUNT = "tree_count";
private static final String REGION_AREAS_CSV = "region_areas.csv"; //$NON-NLS-1$
private static final String ATTRIBUTE_AREAS_CSV = "areas_per_attribute.csv"; //$NON-NLS-1$
private static final String PLOT_WEIGHT = "plot_weight"; //$NON-NLS-1$
private static final String EXPANSION_FACTOR = "expansion_factor"; //$NON-NLS-1$
private static final String TREES_PER_EXP_FACTOR = "trees_per_expansion_factor"; //$NON-NLS-1$
private static final String SHRUBS_PER_EXP_FACTOR = "shrubs_per_expansion_factor"; //$NON-NLS-1$
private final Logger logger = LoggerFactory.getLogger(RegionCalculationUtils.class);
private static final String NO_DATA_LAND_USE = "noData"; //$NON-NLS-1$
@Autowired
EarthSurveyService earthSurveyService;
@Autowired
LocalPropertiesService localPropertiesService;
@Autowired
private BasicDataSource rdbDataSource;
@Autowired
private SchemaService schemaService;
private JdbcTemplate jdbcTemplate;
@PostConstruct
public void initialize() {
jdbcTemplate = new JdbcTemplate(rdbDataSource);
}
public void handleRegionCalculation(){
try {
createWeightFactors();
// If the region_areas.csv is not present then try to add the areas "per attribute" using the file areas_per_attribute.csv
boolean areasAdded = false;
if(!addAreasPerRegion()){
if( addAreasPerAttribute() ){
areasAdded = true;
}
}else{
areasAdded = true;
}
if( areasAdded ){
handleNumberOfTrees();
handleNumberOfShrubs();
recalculatePlotWeights();
}
} catch (Exception e) {
logger.error( "Error when calculating the expansion factors for the plots ", e);
}
}
private void recalculatePlotWeights() {
String schemaName = schemaService.getSchemaPrefix();
List<Double> distinctExpFactors = jdbcTemplate.queryForList("SELECT DISTINCT(" + EXPANSION_FACTOR + ") FROM " + schemaName + "plot", Double.class);
ArrayList<Double> actualExpFactors = new ArrayList<Double>();
for (Object expFactor : distinctExpFactors) {
if( expFactor!= null ){
actualExpFactors.add( (Double) expFactor );
}
}
// Sort in ascending order
Collections.sort(actualExpFactors);
double minimunEF = actualExpFactors.get(0);
for (double expansionFactor : actualExpFactors) {
// The plots with the minimum expansion factor will have a weight of 1
double plotWeight = expansionFactor/minimunEF;
final Object[] updateValues = new Object[2];
updateValues[0] = plotWeight;
updateValues[1] = expansionFactor;
jdbcTemplate.update("UPDATE " + schemaName + "plot SET "+PLOT_WEIGHT+"=? WHERE " + EXPANSION_FACTOR +" =?", updateValues); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
}
}
private void createWeightFactors(){
final String schemaName = schemaService.getSchemaPrefix();
jdbcTemplate.execute("ALTER TABLE " + schemaName + "plot ADD " + EXPANSION_FACTOR + " FLOAT"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
jdbcTemplate.execute("ALTER TABLE " + schemaName + "plot ADD " + PLOT_WEIGHT + " FLOAT"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
}
/**
* This is the "old way"of assigning an expansion factor (the area in hecaters that a plot represents) to a plot based on the information form the "region_areas.csv" file.
* @return True if there was a region_areas.csv file, false if not present so that areas were not assigned.
* @throws SQLException
*/
private boolean addAreasPerRegion() throws SQLException {
final File regionAreas = new File( localPropertiesService.getProjectFolder() + File.separatorChar + REGION_AREAS_CSV);
String schemaName = schemaService.getSchemaPrefix();
if (regionAreas.exists()) {
try {
CSVReader csvReader = CsvReaderUtils.getCsvReader(regionAreas.getAbsolutePath());
String[] csvLine = null;
while( ( csvLine = csvReader.readNext() ) != null ){
try {
String region = csvLine[0];
String plot_file = csvLine[1];
int area_hectars = Integer.parseInt( csvLine[2] );
final Float plot_weight = Float.parseFloat( csvLine[3] );
Object[] parameters = new String[]{region,plot_file};
Integer plots_per_region = jdbcTemplate.queryForObject(
"SELECT count( DISTINCT "+EarthConstants.PLOT_ID+") FROM " + schemaName + "plot WHERE ( region=? OR plot_file=? ) AND land_use_category != '"+NO_DATA_LAND_USE+"' ", parameters,Integer.class); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
Float expansion_factor_hectars_calc = 0f;
if( plots_per_region.intValue() != 0 ){
expansion_factor_hectars_calc = (float)area_hectars / (float) plots_per_region.intValue();
}
final Object[] updateValues = new Object[4];
updateValues[0] = expansion_factor_hectars_calc;
updateValues[1] = plot_weight;
updateValues[2] = region;
updateValues[3] = plot_file;
jdbcTemplate.update("UPDATE " + schemaName + "plot SET "+EXPANSION_FACTOR+"=?, "+PLOT_WEIGHT+"=? WHERE region=? OR plot_file=?", updateValues); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
} catch (NumberFormatException e) {
logger.error("Possibly the header", e); //$NON-NLS-1$
}
}
// FINALLY ASSIGN A WEIGHT OF CERO AND AN EXPANSION FACTOR OF 0 FOR THE PLOTS WITH NO_DATA
final Object[] updateNoDataValues = new Object[3];
updateNoDataValues[0] = 0;
updateNoDataValues[1] = 0;
updateNoDataValues[2] = NO_DATA_LAND_USE;
jdbcTemplate.update("UPDATE " + schemaName + "plot SET "+EXPANSION_FACTOR+"=?, "+PLOT_WEIGHT+"=? WHERE land_use_category=?", updateNoDataValues); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
} catch (FileNotFoundException e) {
logger.error("File not found?", e); //$NON-NLS-1$
} catch (IOException e) {
logger.error("Error reading the CSV file", e); //$NON-NLS-1$
}
return true;
}else{
logger.warn("No CSV region_areas.csv present, calculating areas will not be possible"); //$NON-NLS-1$
return false;
}
}
private void handleNumberOfShrubs() {
String schemaName = schemaService.getSchemaPrefix();
// This is specific to the Global Forest Survey - Drylands monitoring assessment
if( AnalysisSaikuService.surveyContains(SHRUB_COUNT, earthSurveyService.getCollectSurvey() ) ){
// First set the number of shrubs to 30 if the user assessed that there were more than 30 shrubs on the plot
// This way we get a conservative estimation
jdbcTemplate.update("UPDATE " + schemaName + "plot SET "+SHRUB_COUNT+"=30 WHERE many_shrubs=1"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
jdbcTemplate.execute("ALTER TABLE " + schemaName + "plot ADD " + SHRUBS_PER_EXP_FACTOR + " FLOAT"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
jdbcTemplate.update("UPDATE " + schemaName + "plot SET "+SHRUBS_PER_EXP_FACTOR+"="+EXPANSION_FACTOR+"*2*" + SHRUB_COUNT); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
}
}
private void handleNumberOfTrees() {
String schemaName = schemaService.getSchemaPrefix();
// This is specific to the Global Forest Survey - Drylands monitoring assessment
if( AnalysisSaikuService.surveyContains(TREE_COUNT, earthSurveyService.getCollectSurvey() ) ){
// First set the number of shrubs to 30 if the user assessed that there were more than 30 shrubs on the plot
// This way we get a conservative estimation
jdbcTemplate.update("UPDATE " + schemaName + "plot SET "+TREE_COUNT+"=30 WHERE many_trees=1"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
jdbcTemplate.execute("ALTER TABLE " + schemaName + "plot ADD " + TREES_PER_EXP_FACTOR + " FLOAT"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
jdbcTemplate.update("UPDATE " + schemaName + "plot SET "+TREES_PER_EXP_FACTOR+"="+EXPANSION_FACTOR+"*2*" + TREE_COUNT); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
}
}
private boolean addAreasPerAttribute() throws SQLException {
final File areasPerAttribute = new File( localPropertiesService.getProjectFolder() + File.separatorChar + ATTRIBUTE_AREAS_CSV);
String schemaName = schemaService.getSchemaPrefix();
if (areasPerAttribute.exists()) {
try {
CSVReader csvReader = CsvReaderUtils.getCsvReader(areasPerAttribute.getAbsolutePath());
String[] csvLine = null;
// The header (first line) should contain the names of the three columns : attribute_name,area,weight
String[] columnNames = csvReader.readNext();
ArrayList<String> attributeNames = new ArrayList<String>();
if(columnNames.length < 3 ){
throw new RuntimeException("The " + areasPerAttribute.getAbsolutePath() + " file needs have this format : attribute_name1,attribute_name2,...attribute_nameN,area,weight./nAt least one attribute is necessary. This wuuld be the attribute or attributes (their name in the survey definition) that would realte the plot with its expancion factor");
}
for( int colPosition = 0; colPosition<columnNames.length -2; colPosition++){
String attributeName = columnNames[colPosition];
// Validate attribute name
if( !isAttributeInPlotEntity( attributeName ) ){
throw new RuntimeException("The expected format of the CSV file at " + areasPerAttribute.getAbsolutePath() + " should be attribute_name,area,weight. The name of the attribute in hte first column of your CSV '" + attributeName + "'is not a attribute under the plot entity.");
}
attributeNames.add(attributeName);
}
//Validate area and weight headers.
if( !columnNames[ columnNames.length -2 ].equalsIgnoreCase("area") || !columnNames[columnNames.length -1].equalsIgnoreCase("weight")){
throw new RuntimeException("The expected format of the CSV file at " + areasPerAttribute.getAbsolutePath() + " should be attribute_name,area,weight");
}
int line = 1;
while( ( csvLine = csvReader.readNext() ) != null ){
try{
int area_hectars = Integer.parseInt( csvLine[columnNames.length -2] );
final Float plot_weight = Float.parseFloat( csvLine[columnNames.length -1] );
int numberOfAttributes = attributeNames.size();
ArrayList<Object> attributeValues = new ArrayList<Object>();
for(int attributeValueCol = 0; attributeValueCol<numberOfAttributes;attributeValueCol++){
attributeValues.add(csvLine[attributeValueCol]);
}
StringBuffer selectQuery = new StringBuffer();
selectQuery.append("SELECT count( DISTINCT ").append(EarthConstants.PLOT_ID).append(") FROM ").append(schemaName).append("plot WHERE ");
for (int attr =0; attr<attributeNames.size() ; attr++) {
String attributeName = attributeNames.get(attr);
selectQuery.append(attributeName);
if( attr == numberOfAttributes-1 ){
selectQuery.append("=? ");
}else{
selectQuery.append("=? AND ");
}
}
Integer plots_per_region = jdbcTemplate.queryForObject(selectQuery.toString(), attributeValues.toArray(), Integer.class); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
// Calculate the expansion factor. Simply the deivision of the area for the selected attributes by the amount of plots that match the attribute values
Float expansion_factor_hectars_calc = 0f;
if( plots_per_region.intValue() != 0 ){
expansion_factor_hectars_calc = (float)area_hectars / (float) plots_per_region.intValue();
}
// Build the update query
StringBuffer updateQuery = new StringBuffer();
updateQuery.append("UPDATE ").append(schemaName).append("plot SET ").append(EXPANSION_FACTOR).append("=?, ").append(PLOT_WEIGHT).append("=? WHERE ");
for (int attr =0; attr<attributeNames.size() ; attr++) {
String attributeName = attributeNames.get(attr);
updateQuery.append(attributeName);
if( attr == numberOfAttributes-1 ){
updateQuery.append("=? ");
}else{
updateQuery.append("=? AND ");
}
}
// Add the expansion factor and plot_weight to the values that will be sent with the update
attributeValues.add(0, expansion_factor_hectars_calc);
attributeValues.add(1, plot_weight);
jdbcTemplate.update(updateQuery.toString(), attributeValues.toArray()); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
}catch( Exception e5){
logger.error("Problem in line number " + line + " with values " + Arrays.toString( csvLine ), e5 );
}finally{
line++;
}
}
} catch (FileNotFoundException e) {
logger.error("File not found?", e); //$NON-NLS-1$
} catch (IOException e) {
logger.error("Error reading the CSV file", e); //$NON-NLS-1$
}
return true;
}else{
logger.warn("No CSV region_areas.csv present, calculating areas will not be possible"); //$NON-NLS-1$
return false;
}
}
private boolean isAttributeInPlotEntity(String attributeName) {
Schema schema = earthSurveyService.getCollectSurvey().getSchema();
boolean attributeExists = true;
try {
schema.getRootEntityDefinition(EarthConstants.ROOT_ENTITY_NAME ).getChildDefinition(attributeName);
} catch (Exception e) {
// The attribute does not exist under the plot entity
attributeExists = false;
}
return attributeExists;
}
}
|
// CloudCoder - a web-based pedagogical programming environment
// This program is free software: you can redistribute it and/or modify
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
package org.cloudcoder.builder2.server;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import org.cloudcoder.builder2.csandbox.EasySandboxSharedLibrary;
import org.cloudcoder.builder2.javasandbox.JVMKillableTaskManager;
import org.cloudcoder.builder2.pythonfunction.PythonKillableTaskManager;
import org.cloudcoder.daemon.IDaemon;
import org.cloudcoder.daemon.Util;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Implementation of {@link IDaemon} to start, control, and shutdown
* a Builder instance.
*
* @author David Hovemeyer
*/
public class Builder2Daemon implements IDaemon {
private Logger logger = LoggerFactory.getLogger(this.getClass());
private List<BuilderAndThread> builderAndThreadList;
private static class BuilderAndThread {
final Builder2Server builder;
final Thread thread;
public BuilderAndThread(Builder2Server builder, Thread thread) {
this.builder = builder;
this.thread = thread;
}
}
static class Options {
private Properties config;
public Options(Properties config) {
this.config = config;
}
// The default property values are appropriate for running interactively for development.
public String getAppHost() {
return config.getProperty("cloudcoder.submitsvc.oop.host", "localhost");
}
public int getAppPort() {
return Integer.parseInt(config.getProperty("cloudcoder.submitsvc.oop.port", "47374"));
}
public int getNumThreads() {
return Integer.parseInt(config.getProperty("cloudcoder.submitsvc.oop.numThreads", "2"));
}
public String getKeystoreFilename() {
return config.getProperty("cloudcoder.submitsvc.ssl.keystore", "defaultkeystore.jks");
}
public String getKeystorePassword() {
return config.getProperty("cloudcoder.submitsvc.ssl.keystore.password", "changeit");
}
}
/* (non-Javadoc)
* @see org.cloudcoder.daemon.IDaemon#start(java.lang.String)
*/
@Override
public void start(String instanceName) {
// If embedded configuration properties exist, read them
Properties config;
try {
String configPropPath = "cloudcoder.properties";
ClassLoader clsLoader = this.getClass().getClassLoader();
config = Util.loadPropertiesFromResource(clsLoader, configPropPath);
} catch (IllegalStateException e) {
logger.warn("Could not load cloudcoder.properties, using default config properties");
config = new Properties();
}
Options options = new Options(config);
// Create the WebappSocketFactory which the builder tasks can use to create
// connections to the webapp.
WebappSocketFactory webappSocketFactory;
try {
webappSocketFactory = new WebappSocketFactory(
options.getAppHost(),
options.getAppPort(),
options.getKeystoreFilename(),
options.getKeystorePassword());
} catch (Exception e) {
logger.error("Could not create WebappSocketFactory", e);
throw new IllegalStateException("Could not create WebappSocketFactory", e);
}
// Install KillableTaskManager's security manager
JVMKillableTaskManager.installSecurityManager();
PythonKillableTaskManager.installSecurityManager();
logger.info("Builder starting");
logger.info("appHost={}", options.getAppHost());
logger.info("appPort={}", options.getAppPort());
logger.info("numThreads={}", options.getNumThreads());
// Start Builder threads
this.builderAndThreadList = new ArrayList<BuilderAndThread>();
for (int i = 0; i < options.getNumThreads(); i++) {
Builder2Server builder_ = new Builder2Server(webappSocketFactory);
Thread thread_ = new Thread(builder_);
BuilderAndThread builderAndThread = new BuilderAndThread(builder_, thread_);
builderAndThreadList.add(builderAndThread);
builderAndThread.thread.start();
}
}
/* (non-Javadoc)
* @see org.cloudcoder.daemon.IDaemon#handleCommand(java.lang.String)
*/
@Override
public void handleCommand(String command) {
// Right now the Builder has no runtime configuration commands
logger.warn("Builder received unknown command " + command);
}
/* (non-Javadoc)
* @see org.cloudcoder.daemon.IDaemon#shutdown()
*/
@Override
public void shutdown() {
// Shut down all Builder threads
for (BuilderAndThread builderAndThread : builderAndThreadList) {
try {
builderAndThread.builder.shutdown();
builderAndThread.thread.join();
logger.info("Finished");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
// Ensure that if the EasySandbox shared library was built,
// that its directory is deleted before the daemon exits.
EasySandboxSharedLibrary.getInstance().cleanup();
}
}
|
package org.glob3.mobile.generated;
public class MarkEffectTarget implements EffectTarget
{
public void dispose()
{
}
//C++ TO JAVA CONVERTER TODO TASK: There is no preprocessor in Java:
//#if ! C_CODE
public final void unusedMethod()
{
}
//#endif
}
|
package org.glob3.mobile.generated;
public class TileVisitorCache implements ITileVisitor
{
private MultiLayerTileTexturizer _texturizer;
private final TilesRenderParameters _parameters;
private final G3MRenderContext _rc;
private final LayerSet _layerSet;
public TileVisitorCache(MultiLayerTileTexturizer texturizer, TilesRenderParameters parameters, G3MRenderContext rc, LayerSet layerSet)
{
_texturizer = texturizer;
_parameters = parameters;
_rc = rc;
_layerSet = layerSet;
}
public void dispose()
{
}
//C++ TO JAVA CONVERTER WARNING: 'const' methods are not available in Java:
//ORIGINAL LINE: void visitTile(Tile* tile) const
public final void visitTile(Tile tile)
{
TileTextureBuilder ttb = new TileTextureBuilder(_texturizer, _rc, _layerSet, _parameters, _rc.getDownloader(), tile, null, null);
ttb.start();
}
}
|
package fr.masciulli.drinks.fragment;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.SearchView;
import android.widget.TextView;
import java.util.List;
import butterknife.ButterKnife;
import butterknife.InjectView;
import butterknife.OnItemClick;
import de.keyboardsurfer.android.widget.crouton.Crouton;
import de.keyboardsurfer.android.widget.crouton.Style;
import fr.masciulli.drinks.R;
import fr.masciulli.drinks.activity.DrinkDetailActivity;
import fr.masciulli.drinks.activity.MainActivity;
import fr.masciulli.drinks.adapter.DrinksListAdapter;
import fr.masciulli.drinks.data.DrinksProvider;
import fr.masciulli.drinks.model.Drink;
import fr.masciulli.drinks.view.ViewPagerScrollListener;
import retrofit.Callback;
import retrofit.RetrofitError;
import retrofit.client.Response;
public class DrinksListFragment extends Fragment implements Callback<List<Drink>>, ViewPagerScrollListener, SearchView.OnQueryTextListener {
private static final String STATE_LIST = "drinks_list";
@InjectView(R.id.list) ListView mListView;
@InjectView(R.id.progressbar) ProgressBar mProgressBar;
@InjectView(android.R.id.empty) View mEmptyView;
private DrinksListAdapter mListAdapter;
private boolean mLoadingError = false;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
setHasOptionsMenu(true);
final View root = inflater.inflate(R.layout.fragment_drinks_list, container, false);
ButterKnife.inject(this, root);
mListView.setEmptyView(mEmptyView);
mListAdapter = new DrinksListAdapter(getActivity());
mListView.setAdapter(mListAdapter);
if (savedInstanceState != null) {
if (savedInstanceState.containsKey(STATE_LIST)) {
List<Drink> savedDrinks = savedInstanceState.getParcelableArrayList(STATE_LIST);
mListAdapter.update(savedDrinks);
} else {
refresh();
}
} else {
refresh();
}
return root;
}
@OnItemClick(R.id.list)
public void openDrinkDetail(View view, int position) {
Drink drink = mListAdapter.getItem(position);
// Data needed for animations in sub activity
int[] screenLocation = new int[2];
view.getLocationOnScreen(screenLocation);
int orientation = getResources().getConfiguration().orientation;
Intent intent = new Intent(getActivity(), DrinkDetailActivity.class);
intent.
putExtra("drink_name", drink.name).
putExtra("drink_imageurl", drink.imageUrl).
putExtra("drink_id", drink.id).
putExtra("top", screenLocation[1]).
putExtra("height", view.getHeight()).
putExtra("orientation", orientation);
startActivity(intent);
if (!getResources().getBoolean(R.bool.dualpane)) {
getActivity().overridePendingTransition(0, 0);
}
}
@Override
public void success(List<Drink> drinks, Response response) {
mLoadingError = false;
if (getActivity() == null) return;
mListView.setVisibility(View.VISIBLE);
mEmptyView.setVisibility(View.VISIBLE);
mProgressBar.setVisibility(View.GONE);
mListAdapter.update(drinks);
}
@Override
public void failure(RetrofitError retrofitError) {
mLoadingError = true;
if (getActivity() == null) return;
mProgressBar.setVisibility(View.GONE);
mEmptyView.setVisibility(View.VISIBLE);
((MainActivity) getActivity()).setRefreshActionVisible(true);
if (retrofitError.isNetworkError()) {
Crouton.makeText(getActivity(), getString(R.string.network_error), Style.ALERT).show();
} else {
Crouton.makeText(getActivity(), getString(R.string.list_loading_failed), Style.ALERT).show();
}
}
@Override
public void onScroll(int position, float positionOffset, int positionOffsetPixels) {
int first = mListView.getFirstVisiblePosition();
int last = mListView.getLastVisiblePosition();
for (int i = 0; i <= last - first; i++) {
View itemRoot = mListView.getChildAt(i);
if (itemRoot == null) continue;
TextView nameView = (TextView) itemRoot.findViewById(R.id.name);
// TODO get screenWidth somewhere else (always the same)
int screenWidth = itemRoot.getWidth();
int textWidth = nameView.getWidth();
nameView.setRight(Math.round(screenWidth + positionOffset * textWidth));
nameView.setLeft(Math.round(screenWidth - textWidth + positionOffset * textWidth));
}
}
private void refresh() {
mProgressBar.setVisibility(View.VISIBLE);
mEmptyView.setVisibility(View.GONE);
((MainActivity) getActivity()).setRefreshActionVisible(false);
DrinksProvider.getAllDrinks(this);
}
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
super.onCreateOptionsMenu(menu, inflater);
inflater.inflate(R.menu.drinks_list, menu);
// SearchView configuration
final MenuItem searchMenuItem = menu.findItem(R.id.search);
if (mLoadingError) {
((MainActivity) getActivity()).setRefreshActionVisible(true);
}
SearchView searchView = (SearchView) searchMenuItem.getActionView();
searchView.setQueryHint(getString(R.string.search_hint));
searchView.setOnQueryTextListener(this);
}
@Override
public boolean onQueryTextSubmit(String s) {
return false;
}
@Override
public boolean onQueryTextChange(String s) {
if (mListView != null) {
mListAdapter.getFilter().filter(s);
}
return true;
}
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
if (mListAdapter.getCount() > 0) {
outState.putParcelableArrayList(STATE_LIST, mListAdapter.getDrinks());
}
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.retry:
refresh();
return true;
}
return super.onOptionsItemSelected(item);
}
}
|
package com.example.bot.spring;
import java.util.Arrays;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;
import lombok.extern.slf4j.Slf4j;
// The following code contains a bug in it. You need to fix it in Lab 2 in
// order to make it work.
// After you fix the code, the bot should be able to response based on
// database.txt located in
// sample-spring-boot-kitchensink/resources/static/database.txt.
// This file contains a few lines with the format <input>:<output>.
// The program below wish to perform an exact word match the input text
// against the <input> against each line. The bot should replys
// "XXX says <output>"
// For instance, if the client sends "abc", the bot should reply
// "kevinw says def"
// If you registered your ITSC login as kevinw.
@Slf4j
public class DatabaseEngine {
String search(String text) throws Exception {
String result = null;
BufferedReader br = null;
InputStreamReader isr = null;
try {
isr = new InputStreamReader(
this.getClass().getResourceAsStream(FILENAME));
br = new BufferedReader(isr);
String sCurrentLine;
while (result == null && (sCurrentLine = br.readLine()) != null) {
String[] parts = sCurrentLine.split(":");
if (text.toLowerCase().equals(parts[0].toLowerCase())) {
result = parts[1];
}
}
} catch (IOException e) {
log.info("IOException while reading file: {}", e.toString());
} finally {
try {
if (br != null)
br.close();
if (isr != null)
isr.close();
} catch (IOException ex) {
log.info("IOException while closing file: {}", ex.toString());
}
}
if (result != null)
return result;
throw new Exception("NOT FOUND");
}
private final String FILENAME = "/static/database.txt";
}
|
package org.springframework.beans.factory.access;
import java.lang.reflect.Method;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanFactoryPostProcessor;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.util.Assert;
import org.springframework.util.ClassUtils;
/**
* A bean-factory post processor configured to trigger the instantiation and
* configuration of a global service locator from a Spring application context.
* <p>
* <p>
* This allows for the locator and the services it provides access to to be
* configured via Spring just like any other bean. In addition, as a
* <code>BeanFactoryPostProcessor</code> this class ensures locators are
* instantiated before the objects that use them. This is often necessary when
* objects access the locator through a convenient static accessors (e.g.
* getInstance()), as opposed to having a reference to the locator injected
* through a setter or constructor.
* <p>
* <p>
* There are two different ways to load a singleton service locator:
* <ol>
* <li>By specifying one or more bean id references in the application context
* that point to locators with static load() methods. In this case, the load()
* method is called directly on the locator instance to configure the singleton
* instance. For example:
*
* <pre>
* <bean id="serviceLocatorLoader"
* class="com.csi.commons.utils.beans.SingletonServiceLocatorLoader">
* <constructor-arg index="0">
* <listgt;
* <value>consoleServices</value>
* </list>
* </constructor-arg>
* </bean>
* </pre>
*
* ... will call the static <code>load</code> method on the
* <code>ConsoleServices</code> class, passing in the configured
* <code>consoleServices</code> bean.
*
* <li>By specifying one or more singleton locator accessor classes with the
* bean ID that corresponds to the instance to be loaded and shared. In this
* case, load is called on the singleton locator accessor, and not the locator
* itself. This approach completely abstracts away singleton status from the
* locator class. As an example:
* </ol>
*
* <pre>
* <bean id="serviceLocatorLoader"
* class="com.csi.commons.utils.beans.SingletonServiceLocatorLoader">
* <constructor-arg index="0">
* <listgt;
* <value>consoleServices@com.acme.ConsoleServicesSingletonLocator</value>
* </list>
* </constructor-arg>
* </bean>
* </pre>
*
* ... will call the static <code>load</code> method on the
* <code>ConsoleServicesSingletonLocator</code> class, passing in the
* configured <code>consoleServices</code> bean.
*
* Note - take care not to abuse this pattern. Generally dependency
* injection/IoC should be preferred to singleton, getInstance() style lookup.
*
* @author Keith Donald
*/
public class SingletonServiceLocatorLoader implements BeanFactoryPostProcessor {
private static final Log logger = LogFactory
.getLog(SingletonServiceLocatorLoader.class);
public String[] locatorBeanIds;
private String loadMethodName = "load";
private static final char CLASS_SEPARATOR = '@';
/**
* Creates a SingletonServiceLocatorLoader that loads the specified services
* using a static <code>load</code> method.
*
* @param beanIds
* The configured service locator bean ids.
*/
public SingletonServiceLocatorLoader(String[] beanIds) {
Assert.hasElements(beanIds);
this.locatorBeanIds = beanIds;
}
/**
* Set the name of the static load method to call to configure locators
* with the shared bean instance.
*
* @param loadMethodName
* The load method name, <code>load</code> is used by default.
*/
public void setLoadMethodName(String loadMethodName) {
Assert.notNull(loadMethodName);
this.loadMethodName = loadMethodName;
}
/**
* @see org.springframework.beans.factory.config.BeanFactoryPostProcessor#postProcessBeanFactory
*/
public void postProcessBeanFactory(
ConfigurableListableBeanFactory beanFactory) throws BeansException {
for (int i = 0; i < locatorBeanIds.length; i++) {
logger
.info("Instantating locator bean '" + locatorBeanIds[i]
+ "'");
String locatorBeanId = locatorBeanIds[i];
Object locatorInstance = null;
Class globalLocatorClass = null;
int classSep = locatorBeanId.indexOf(CLASS_SEPARATOR);
if (classSep == -1) {
// no class specified, use locator class to load singleton
// instance
locatorInstance = beanFactory.getBean(locatorBeanIds[i]);
globalLocatorClass = locatorInstance.getClass();
} else {
// singleton class specified, use it to load shared instance
try {
locatorInstance = beanFactory.getBean(locatorBeanId
.substring(0, classSep));
globalLocatorClass = Class.forName(locatorBeanId
.substring(classSep + 1));
} catch (ClassNotFoundException e) {
logger.warn("No class found '"
+ locatorBeanId.substring(0, classSep) + "'");
logger
.warn("The singleton locator expression must be in the form <sharedBeanIdToLoad@singletonServiceLocatorAccessorClassName>");
}
}
if (locatorInstance == null || globalLocatorClass == null) {
return;
}
Method loadMethod = getStaticLoadMethod(globalLocatorClass,
locatorInstance);
if (loadMethod == null) {
logger
.warn("No public static 'load' method found on singleton service locator '"
+ globalLocatorClass + "'");
}
try {
loadMethod.invoke(null, new Object[] { locatorInstance });
} catch (Exception e) {
logger.warn("Unable to load locator '" + locatorInstance + "'",
e);
}
}
}
private Method getStaticLoadMethod(Class globalLocatorClass, Object instance) {
Class[] args = new Class[] { instance.getClass() };
Method method = ClassUtils.getStaticMethod(loadMethodName,
globalLocatorClass, args);
if (method == null) {
Class[] interfaces = instance.getClass().getInterfaces();
for (int i = 0; i < interfaces.length; i++) {
args[0] = interfaces[i];
method = ClassUtils.getStaticMethod(loadMethodName,
globalLocatorClass, args);
if (method != null) {
break;
}
}
}
return method;
}
}
|
package gov.nih.nci.codegen.util;
import gov.nih.nci.codegen.GenerationException;
import gov.nih.nci.codegen.validator.ValidatorAttribute;
import gov.nih.nci.codegen.validator.ValidatorClass;
import gov.nih.nci.codegen.validator.ValidatorModel;
import gov.nih.nci.ncicb.xmiinout.domain.UMLAssociation;
import gov.nih.nci.ncicb.xmiinout.domain.UMLAssociationEnd;
import gov.nih.nci.ncicb.xmiinout.domain.UMLAttribute;
import gov.nih.nci.ncicb.xmiinout.domain.UMLClass;
import gov.nih.nci.ncicb.xmiinout.domain.UMLDatatype;
import gov.nih.nci.ncicb.xmiinout.domain.UMLDependency;
import gov.nih.nci.ncicb.xmiinout.domain.UMLGeneralization;
import gov.nih.nci.ncicb.xmiinout.domain.UMLInterface;
import gov.nih.nci.ncicb.xmiinout.domain.UMLModel;
import gov.nih.nci.ncicb.xmiinout.domain.UMLPackage;
import gov.nih.nci.ncicb.xmiinout.domain.UMLTaggableElement;
import gov.nih.nci.ncicb.xmiinout.domain.UMLTaggedValue;
import gov.nih.nci.ncicb.xmiinout.domain.bean.UMLAssociationEndBean;
import gov.nih.nci.ncicb.xmiinout.util.ModelUtil;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import java.util.StringTokenizer;
import java.util.Vector;
import java.util.regex.Pattern;
import org.apache.log4j.Logger;
import org.jdom.Element;
import gov.nih.nci.iso21090.hibernate.node.*;
public class TransformerUtils
{
private static Logger log = Logger.getLogger(TransformerUtils.class);
private String BASE_PKG_LOGICAL_MODEL;
private String BASE_PKG_DATA_MODEL;
private String INCLUDE_PACKAGE;
private String EXCLUDE_PACKAGE;
private String EXCLUDE_NAME;
private String EXCLUDE_NAMESPACE;
private String IDENTITY_GENERATOR_TAG;
private Set<String> INCLUDE_PACKAGE_PATTERNS = new HashSet<String>();
private Set<String> EXCLUDE_PACKAGE_PATTERNS = new HashSet<String>();
private Set<String> EXCLUDE_CLASS_PATTERNS = new HashSet<String>();
private Set<String> EXCLUDE_NAMESPACE_PATTERNS = new HashSet<String>();
private String DATABASE_TYPE;
private Map<String,String> CASCADE_STYLES = new HashMap<String,String>();
private ValidatorModel vModel;
private ValidatorModel vModelExtension;
private String namespaceUriPrefix;
private boolean useGMETags = false;
private boolean isJaxbEnabled = false;
private boolean isISO21090Enabled = false;
private UMLPackage isoDataTypeRootPackage;
/**
* UMLModel from which the code is to be generated
*/
private UMLModel model;
public static final String TV_ID_ATTR_COLUMN = "id-attribute";
public static final String TV_MAPPED_ATTR_COLUMN = "mapped-attributes";
public static final String TV_MAPPED_ATTR_CONSTANT = "mapped-constant";
public static final String TV_ASSOC_COLUMN = "implements-association";
public static final String TV_INVERSE_ASSOC_COLUMN = "inverse-of";
public static final String TV_DISCR_COLUMN = "discriminator";
public static final String TV_CORRELATION_TABLE = "correlation-table";
public static final String TV_DOCUMENTATION = "documentation";
public static final String TV_DESCRIPTION = "description";
public static final String TV_LAZY_LOAD = "lazy-load";
public static final String TV_TYPE="type";
public static final String TV_MAPPED_COLLECTION_TABLE = "mapped-collection-table";
public static final String TV_MAPPED_ELEMENT_COLUMN = "mapped-element";
public static final String TV_CADSR_PUBLICID = "CADSR_ConceptualDomainPublicID";
public static final String TV_CADSR_VERSION = "CADSR_ConceptualDomainVersion";
public static final String TV_NCI_CASCADE_ASSOCIATION = "NCI_CASCADE_ASSOCIATION";
public static final String TV_NCI_EAGER_LOAD = "NCI_EAGER_LOAD";
public static final String TV_PK_GENERATOR = "NCI_GENERATOR.";
public static final String TV_PK_GENERATOR_PROPERTY = "NCI_GENERATOR_PROPERTY";
public static final String TV_MAPPED_COLLECTION_ELEMENT_TYPE = "mapped-collection-element-type";
public static final String TV_NCI_GME_XML_NAMESPACE = "NCI_GME_XML_NAMESPACE"; //Used for projects, Packages, Classes
public static final String TV_NCI_GME_XML_ELEMENT = "NCI_GME_XML_ELEMENT"; //Used for Classes
public static final String TV_NCI_GME_XML_LOC_REF = "NCI_GME_XML_LOC_REF"; //Used for Attributes
public static final String TV_NCI_GME_SOURCE_XML_LOC_REF = "NCI_GME_SOURCE_XML_LOC_REF"; //Used for Associations
public static final String TV_NCI_GME_TARGET_XML_LOC_REF = "NCI_GME_TARGET_XML_LOC_REF"; //Used for Associations
public static final String STEREO_TYPE_TABLE = "table";
public static final String STEREO_TYPE_DATASOURCE_DEPENDENCY = "DataSource";
public static final String PK_GENERATOR_SYSTEMWIDE = "NCI_GENERATOR_SYSTEMWIDE.";
public static final String ISO_ROOT_PACKAGE_NAME = "gov.nih.nci.iso21090";
public static final Map<String, String> javaDatatypeMap = new HashMap<String, String>()
{
{
put("int", "Integer");
put("integer", "Integer");
put("double", "Double");
put("float", "Float");
put("long", "Long");
put("string", "String");
put("char", "Character");
put("character", "Character");
put("boolean", "Boolean");
put("byte", "Byte");
put("byte[]", "Byte[]");
put("short", "Short");
put("date", "java.util.Date");
put("java.util.date", "java.util.Date");
put("collection<int>", "Collection<Integer>");
put("collection<integer>", "Collection<Integer>");
put("collection<double>", "Collection<Double>");
put("collection<float>", "Collection<Float>");
put("collection<long>", "Collection<Long>");
put("collection<string>", "Collection<String>");
put("collection<boolean>", "Collection<Boolean>");
put("collection<byte>", "Collection<Byte>");
put("collection<short>", "Collection<Short>");
put("collection<char>", "Collection<Character>");
put("collection<character>", "Collection<Character>");
}
};
public static final Map<String, String> isoDatatypeMap = new HashMap<String, String>()
{
{
put("BL", "Bl");
put("BL.NONNULL", "BlNonNull");
put("ST", "St");
put("ST.NT", "StNt");
put("II", "Ii");
put("TEL", "Tel");
put("TEL.PERSON", "TelPerson");
put("TEL.URL", "TelUrl");
put("TEL.PHONE", "TelPhone");
put("TEL.EMAIL", "TelEmail");
put("ED", "Ed");
put("ED.TEXT", "EdText");
put("CD", "Cd");
put("SC", "Sc");
put("INT", "Int");
put("REAL", "Real");
put("TS", "Ts");
put("PQV", "Pqv");
put("PQ", "Pq");
put("IVL<INT>", "Ivl<Int>");
put("IVL<REAL>", "Ivl<Real>");
put("IVL<TS>", "Ivl<Ts>");
put("IVL<PQV>", "Ivl<Pqv>");
put("IVL<PQ>", "Ivl<Pq>");
put("EN", "En");
put("EN.PN", "EnPn");
put("EN.ON", "EnOn");
put("DSET<II>", "DSet<Ii>");
put("DSET<TEL>", "DSet<Tel>");
put("DSET<CD>", "DSet<Cd>");
put("DSET<AD>", "DSet<Ad>");
put("AD", "Ad");
}
};
public static final Map<String, String> isoDatatypeCompleteMap = new HashMap<String, String>()
{
{
put("BL", "Bl");
put("BL.NONNULL", "BlNonNull");
put("ST", "St");
put("ST.NT", "StNt");
put("II", "Ii");
put("TEL", "Tel");
put("TEL.PERSON", "TelPerson");
put("TEL.URL", "TelUrl");
put("TEL.PHONE", "TelPhone");
put("TEL.EMAIL", "TelEmail");
put("ED", "Ed");
put("ED.TEXT", "EdText");
put("CD", "Cd");
put("SC", "Sc");
put("INT", "Int");
put("REAL", "Real");
put("TS", "Ts");
put("PQV", "Pqv");
put("PQ", "Pq");
put("IVL<INT>", "Ivl<Int>");
put("IVL<REAL>", "Ivl<Real>");
put("IVL<TS>", "Ivl<Ts>");
put("IVL<PQV>", "Ivl<Pqv>");
put("IVL<PQ>", "Ivl<Pq>");
put("EN", "En");
put("EN.PN", "EnPn");
put("EN.ON", "EnOn");
put("DSET<II>", "DSet<Ii>");
put("DSET<TEL>", "DSet<Tel>");
put("DSET<CD>", "DSet<Cd>");
put("DSET<AD>", "DSet<Ad>");
put("AD", "Ad");
put("ADXP.AL", "AdxpAl");
put("ADXP.ADL", "AdxpAdl");
put("ADXP.UNID", "AdxpUnid");
put("ADXP.UNIT", "AdxpUnit");
put("ADXP.DAL", "AdxpDal");
put("ADXP.DINST", "AdxpDinst");
put("ADXP.DINSTA", "AdxpDinsta");
put("ADXP.DINSTQ", "AdxpDinstq");
put("ADXP.DMOD", "AdxpDmod");
put("ADXP.DMODID", "AdxpDmodid");
put("ADXP.SAL", "AdxpSal");
put("ADXP.BNR", "AdxpBnr");
put("ADXP.BNN", "AdxpBnn");
put("ADXP.BNS", "AdxpBns");
put("ADXP.STR", "AdxpStr");
put("ADXP.STB", "AdxpStb");
put("ADXP.STTYP", "AdxpSttyp");
put("ADXP.DIR", "AdxpDir");
put("ADXP.INT", "AdxpInt");
put("ADXP.CAR", "AdxpCar");
put("ADXP.CEN", "AdxpCen");
put("ADXP.CNT", "AdxpCnt");
put("ADXP.CPA", "AdxpCpa");
put("ADXP.CTY", "AdxpCty");
put("ADXP.DEL", "AdxpDel");
put("ADXP.POB", "AdxpPob");
put("ADXP.PRE", "AdxpPre");
put("ADXP.STA", "AdxpSta");
put("ADXP.ZIP", "AdxpZip");
put("ADXP", "Adxp");
put("ENXP", "Enxp");
put("DSET", "DSet");
put("IVL", "Ivl");
}
};
public TransformerUtils(Properties umlModelFileProperties,Properties transformerProperties,List cascadeStyles, ValidatorModel vModel, ValidatorModel vModelExtension, UMLModel model) {
BASE_PKG_LOGICAL_MODEL = umlModelFileProperties.getProperty("Logical Model") == null ? "" :umlModelFileProperties.getProperty("Logical Model").trim();
BASE_PKG_DATA_MODEL = umlModelFileProperties.getProperty("Data Model")==null ? "" : umlModelFileProperties.getProperty("Data Model").trim();
EXCLUDE_PACKAGE = umlModelFileProperties.getProperty("Exclude Package")==null ? "" : umlModelFileProperties.getProperty("Exclude Package").trim();
INCLUDE_PACKAGE = umlModelFileProperties.getProperty("Include Package")==null ? "" : umlModelFileProperties.getProperty("Include Package").trim();
EXCLUDE_NAME = umlModelFileProperties.getProperty("Exclude Name")==null ? "" : umlModelFileProperties.getProperty("Exclude Name").trim();
EXCLUDE_NAMESPACE = umlModelFileProperties.getProperty("Exclude Namespace")==null ? "" : umlModelFileProperties.getProperty("Exclude Namespace").trim();
namespaceUriPrefix = transformerProperties.getProperty("namespaceUriPrefix")==null ? "" : transformerProperties.getProperty("namespaceUriPrefix").trim().replace(" ", "_");
useGMETags = transformerProperties.getProperty("useGMETags")==null ? false : Boolean.parseBoolean(transformerProperties.getProperty("useGMETags"));
isJaxbEnabled = transformerProperties.getProperty("isJaxbEnabled")==null ? false : Boolean.parseBoolean(transformerProperties.getProperty("isJaxbEnabled"));
isISO21090Enabled = transformerProperties.getProperty("isISO21090Enabled")==null ? false : Boolean.parseBoolean(transformerProperties.getProperty("isISO21090Enabled"));
this.model = model;
if (useGMETags){
setModelNamespace(model,this.getBasePkgLogicalModel());
}
for(String excludeToken:EXCLUDE_PACKAGE.split(","))
EXCLUDE_PACKAGE_PATTERNS.add(excludeToken.trim());
for(String includeToken:INCLUDE_PACKAGE.split(","))
INCLUDE_PACKAGE_PATTERNS.add(includeToken.trim());
for(String excludeToken:EXCLUDE_NAME.split(","))
EXCLUDE_CLASS_PATTERNS.add(excludeToken.trim());
for(String excludeToken:EXCLUDE_NAMESPACE.split(","))
EXCLUDE_NAMESPACE_PATTERNS.add(excludeToken.trim());
IDENTITY_GENERATOR_TAG = umlModelFileProperties.getProperty("Identity Generator Tag") == null ? "": umlModelFileProperties.getProperty("Identity Generator Tag").trim();
DATABASE_TYPE = umlModelFileProperties.getProperty("Database Type") == null ? "": umlModelFileProperties.getProperty("Database Type").trim();
for (Object cascadeStyle : cascadeStyles){
CASCADE_STYLES.put((String) cascadeStyle, (String)cascadeStyle);
}
this.vModel = vModel;
log.debug("ValidatorModel: " + vModel);
this.vModelExtension = vModelExtension;
log.debug("ValidatorModel Extension: " + vModelExtension);
}
private void setModelNamespace(UMLModel model, String basePkgLogicalModel){
//override codegen.properties NAMESPACE_PREFIX property with GME namespace tag value, if it exists
try {
String namespaceUriPrefix = this.getModelNamespace(model, basePkgLogicalModel);
if (namespaceUriPrefix != null) {
this.namespaceUriPrefix = namespaceUriPrefix;
}
} catch (GenerationException e) {
log.error("Exception caught trying to set GME model namespace URI Prefix: ", e);
}
}
public String getDatabaseType() {
return DATABASE_TYPE;
}
public boolean isIncluded(UMLClass klass) throws GenerationException
{
String fqcn = getFQCN(klass);
return isIncluded(fqcn);
}
public boolean isIncluded(UMLInterface interfaze) throws GenerationException
{
String fqcn = getFQCN(interfaze);
return isIncluded(fqcn);
}
public boolean isIncluded(String fqcn)
{
log.debug("isIncluded(String fqcn) for fqcn: "+fqcn);
for (String excludePkgPattern:EXCLUDE_PACKAGE_PATTERNS)
if (Pattern.matches(excludePkgPattern, fqcn))
return false;
for (String excludeClassPattern:EXCLUDE_CLASS_PATTERNS){
if (Pattern.matches(excludeClassPattern, fqcn))
return false;
}
for(String includePkgPattern: INCLUDE_PACKAGE_PATTERNS){
log.debug("includePkgPattern: "+includePkgPattern+"; fqcn: "+fqcn);
if(Pattern.matches(includePkgPattern, fqcn))
return true;
}
return false;
}
public boolean isIncluded(UMLPackage pkg) throws GenerationException
{
String fullPkgName = getFullPackageName(pkg);
log.debug("isIncluded(UMLPackage pkg) for fullPkgName: "+fullPkgName);
for(String excludePkgPattern: EXCLUDE_PACKAGE_PATTERNS)
if (Pattern.matches(excludePkgPattern, fullPkgName))
return false;
for(String includePkgPattern: INCLUDE_PACKAGE_PATTERNS)
if (Pattern.matches(includePkgPattern, fullPkgName))
return true;
return true;
}
public boolean isNamespaceIncluded(UMLClass klass, String defaultNamespacePrefix) throws GenerationException
{
String pkgNamespace=null;
try {
pkgNamespace = getGMENamespace(klass);
} catch (GenerationException ge) {
log.error("ERROR: ", ge);
throw new GenerationException("Error getting the GME Namespace tag value for: " + getFullPackageName(klass.getPackage()), ge);
}
if (pkgNamespace==null) //use default namespace
pkgNamespace = defaultNamespacePrefix+getFullPackageName(klass);
log.debug("* * * * * pkgNamespace:"+pkgNamespace);
for(String excludePkgNamespacePattern: EXCLUDE_NAMESPACE_PATTERNS)
if(Pattern.matches(excludePkgNamespacePattern,pkgNamespace)){
return false;
}
return true;
}
public String getEmptySpace(Integer count)
{
String spaces = "";
for(Integer i=0;i<count;i++)
spaces +="\t";
return spaces;
}
public String getFQEN(UMLTaggableElement elt) throws GenerationException {
if (elt instanceof UMLClass)
return getFQCN((UMLClass)elt);
if (elt instanceof UMLPackage)
return getFullPackageName((UMLPackage)elt);
throw new GenerationException("Error getting fully qualified element name. Supported taggable element types include UMLClass and UMLPackage; element is neither");
}
public String getFQCN(UMLClass klass)
{
return removeBasePackage(ModelUtil.getFullName(klass));
}
public String getFQCN(UMLInterface interfaze)
{
return removeBasePackage(ModelUtil.getFullName(interfaze));
}
public String getFullPackageName(UMLTaggableElement te)
{
if (te instanceof UMLClass)
return removeBasePackage(ModelUtil.getFullPackageName((UMLClass)te));
if (te instanceof UMLInterface)
return removeBasePackage(ModelUtil.getFullPackageName((UMLInterface)te));
if (te instanceof UMLPackage)
return removeBasePackage(ModelUtil.getFullPackageName((UMLPackage)te));
return "";
}
private String removeBasePackage(String path)
{
if(path.startsWith(BASE_PKG_LOGICAL_MODEL+"."))
return path.substring(BASE_PKG_LOGICAL_MODEL.length()+1);
else if(path.startsWith(BASE_PKG_DATA_MODEL+"."))
return path.substring(BASE_PKG_DATA_MODEL.length()+1);
else
return path;
}
public String getBasePkgLogicalModel(){
return BASE_PKG_LOGICAL_MODEL;
}
public String getBasePkgDataModel(){
return BASE_PKG_DATA_MODEL;
}
public UMLClass getSuperClass(UMLClass klass) throws GenerationException
{
UMLClass[] superClasses = ModelUtil.getSuperclasses(klass);
if(superClasses.length == 0) {
log.debug("*** Getting superclass for class " + klass.getName() + ": " + null);
return null;
}
if(superClasses.length > 1)
throw new GenerationException("Class can not have more than one super class");
log.debug("*** Getting superclass for class " + klass.getName() + ": " + superClasses[0].getName());
return superClasses[0];
}
public String getSuperClassString(UMLClass klass) throws GenerationException
{
UMLClass superClass = getSuperClass(klass);
if(superClass == null)
if (isJaxbEnabled()){
return "";
} else {
return "";
}
else
return "extends " + superClass.getName();
}
public UMLInterface[] getSuperInterface(UMLInterface interfaze) throws GenerationException
{
UMLInterface[] superInterfaces = ModelUtil.getSuperInterfaces(interfaze);
if(superInterfaces.length == 0) {
log.debug("*** Getting superinterface for interface " + interfaze.getName() + ": " + null);
return null;
}
log.debug("*** Getting superinterface for interface " + interfaze.getName() + ": " + superInterfaces[0].getName());
return superInterfaces;
}
public String getSuperInterfaceString(UMLInterface interfaze) throws GenerationException
{
String superInterfaceStr = "extends ";
UMLInterface[] superInterfaces = getSuperInterface(interfaze);
if(superInterfaces == null)
return "";
else {
superInterfaceStr += superInterfaces[0].getName();
for (int i = 1; i < superInterfaces.length; i++){
superInterfaceStr += ", " + superInterfaces[i].getName();
}
}
return superInterfaceStr;
}
public UMLInterface[] getInterfaces(UMLClass klass) throws GenerationException
{
UMLInterface[] interfaces = ModelUtil.getInterfaces(klass);
if(interfaces.length == 0) {
log.debug("*** Getting interface for class " + klass.getName() + ": " + null);
return null;
}
log.debug("*** Getting superclass for class " + klass.getName() + ": " + interfaces[0].getName());
return interfaces;
}
public String getInterfaceString(UMLClass klass) throws GenerationException
{
UMLInterface[] interfaces = getInterfaces(klass);
if(interfaces == null)
return "";
else {
String interfaceStr = "";
for (UMLInterface interfaze : interfaces){
interfaceStr += ", " + interfaze.getName();
}
return interfaceStr;
}
}
public String getInterfaceImports(UMLInterface interfaze) throws GenerationException
{
StringBuilder sb = new StringBuilder();
Set<String> importList = new HashSet<String>();
UMLInterface[] interfaces = ModelUtil.getSuperInterfaces(interfaze);
String pkgName = getFullPackageName(interfaze);
for (UMLInterface superInterfaze : interfaces) {
String superInterfacePkg = getFullPackageName(superInterfaze);
if (!pkgName.equals(superInterfacePkg))
importList.add(getFQCN(superInterfaze));
}
for(String importClass:importList)
sb.append("import ").append(importClass).append(";\n");
return sb.toString();
}
public String getImports(UMLClass klass) throws GenerationException
{
StringBuilder sb = new StringBuilder();
Set<String> importList = new HashSet<String>();
UMLClass[] superClasses = ModelUtil.getSuperclasses(klass);
UMLInterface[] interfaces = ModelUtil.getInterfaces(klass);
if(superClasses.length>1)
throw new GenerationException("Class can not have more than one super classes");
String pkgName = getFullPackageName(klass);
if(superClasses.length == 1)
{
String superPkg = getFullPackageName(superClasses[0]);
if(!pkgName.equals(superPkg))
importList.add(getFQCN(superClasses[0]));
}
for (UMLInterface interfaze : interfaces) {
String interfacePkg = getFullPackageName(interfaze);
if (!pkgName.equals(interfacePkg))
importList.add(getFQCN(interfaze));
}
for(UMLAttribute attr: klass.getAttributes())
{
if(getDataType(attr).startsWith("Collection") && !importList.contains("java.util.Collection"))
{
importList.add("java.util.Collection");
break;
}
}
if(isISO21090Enabled)
{
for(UMLAttribute attr: klass.getAttributes())
{
String javaName = isoDatatypeMap.get(attr.getDatatype().getName());
if(javaName!=null && javaName.indexOf("<")>0)
{
String collectionType = javaName.substring(0,javaName.indexOf("<"));
String collectionElementType = javaName.substring(javaName.indexOf("<")+1,javaName.indexOf(">"));
//String collectionName = isoDatatypeMap.get(collectionType);
if (!importList.contains("gov.nih.nci.iso21090."+collectionType))
importList.add("gov.nih.nci.iso21090."+collectionType);
javaName = collectionElementType;
}
if(javaName!=null && !importList.contains("gov.nih.nci.iso21090."+javaName))
{
importList.add("gov.nih.nci.iso21090."+javaName);
}
}
}
for(UMLAssociation association: klass.getAssociations())
{
List<UMLAssociationEnd> assocEnds = association.getAssociationEnds();
UMLAssociationEnd otherEnd = getOtherEnd(klass,assocEnds);
String assocKlass = getFQCN ((UMLClass)otherEnd.getUMLElement());
if(!pkgName.equals(getFullPackageName ((UMLClass)otherEnd.getUMLElement())) && !importList.contains(assocKlass))
importList.add(assocKlass);
if(isAssociationEndMany(otherEnd) && otherEnd.isNavigable()&& !importList.contains("java.util.Collection"))
importList.add("java.util.Collection");
}
importList.addAll(getHibernateValidatorConstraintImports(klass));
for(String importClass:importList)
sb.append("import ").append(importClass).append(";\n");
if (isJaxbEnabled){
sb.append("\n");
sb.append("import com.sun.xml.bind.CycleRecoverable;\n");
if(isISO21090Enabled) {
sb.append("import gov.nih.nci.system.client.util.xml.JAXBISOAdapter;\n");
sb.append("import gov.nih.nci.system.client.util.xml.JAXBISOIvlPqAdapter;\n");
sb.append("import gov.nih.nci.system.client.util.xml.JAXBISOIvlRealAdapter;\n");
sb.append("import gov.nih.nci.system.client.util.xml.JAXBISOIvlTsAdapter;\n");
sb.append("import gov.nih.nci.system.client.util.xml.JAXBISOIvlIntAdapter;\n");
}
sb.append("import javax.xml.bind.annotation.XmlAccessType;\n");
sb.append("import javax.xml.bind.annotation.XmlAccessorType;\n");
sb.append("import javax.xml.bind.annotation.XmlAttribute;\n");
sb.append("import javax.xml.bind.annotation.XmlElementWrapper;\n");
sb.append("import javax.xml.bind.annotation.XmlElement;\n");
sb.append("import javax.xml.bind.annotation.XmlRootElement;\n");
sb.append("import javax.xml.bind.annotation.XmlSeeAlso;\n");
sb.append("import javax.xml.bind.annotation.XmlTransient;\n");
sb.append("import javax.xml.bind.annotation.XmlType;\n");
sb.append("import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;\n");
sb.append("\n");
}
sb.append("import java.io.Serializable;\n");
return sb.toString();
}
public String getJaxbXmlTransientAnnotation(){
return " @XmlTransient";
}
public String getJaxbCollectionAnnotations(UMLClass klass, UMLClass assocKlass, String rolename){
StringBuilder sb = new StringBuilder();
sb.append(" @XmlElementWrapper(name=\"").append(rolename).append("\",\n");
sb.append(" namespace=\"").append(getNamespaceUriPrefix()).append(getFullPackageName(klass)).append("\")\n");
sb.append(" @XmlElement(name=\"").append(assocKlass.getName()).append("\",\n");
sb.append(" namespace=\"").append(getNamespaceUriPrefix()).append(getFullPackageName(assocKlass)).append("\")");
return sb.toString();
}
public String getDataType(UMLAttribute attr)
{
UMLDatatype dataType = attr.getDatatype();
String name = dataType.getName();
if(dataType instanceof UMLClass)
name = getFQCN((UMLClass)dataType);
if(name.startsWith("java.lang."))
name = name.substring("java.lang.".length());
if(name.startsWith(ISO_ROOT_PACKAGE_NAME+"."))
name = name.substring((ISO_ROOT_PACKAGE_NAME+".").length());
String returnValue = null;
if(isISO21090Enabled)
returnValue = isoDatatypeMap.get(name);
if(returnValue == null)
returnValue = javaDatatypeMap.get(name.toLowerCase());
return returnValue == null ? "" : returnValue;
}
public HashMap<String, String> getPKGeneratorTags(UMLClass table,String fqcn,UMLAttribute classIdAttr) throws GenerationException {
HashMap<String, String> pkTags = new HashMap<String, String>();
String pkgenClassKey = TV_PK_GENERATOR + DATABASE_TYPE;
UMLAttribute tableIdAttribute=getMappedColumn(table,fqcn+"."+classIdAttr.getName());
Collection<UMLTaggedValue> tableTaggedValues = tableIdAttribute.getTaggedValues();
String pkGeneratorClass = getTagValue(tableTaggedValues,pkgenClassKey, 1);
if (pkGeneratorClass != null && !("".equals(pkGeneratorClass))) {
for (int i = 1; i <= tableTaggedValues.size(); i++) {
String pkgenProp = TV_PK_GENERATOR_PROPERTY + i + "."+ DATABASE_TYPE;
String pkParam = getTagValue(tableTaggedValues, pkgenProp, 1);
StringTokenizer tokenizer = new StringTokenizer(pkParam, ":");
if(tokenizer.hasMoreTokens()){
pkTags.put(tokenizer.nextToken(), tokenizer.nextToken());
}
}
pkTags.put(pkgenClassKey, pkGeneratorClass);
} else {
pkTags.put(PK_GENERATOR_SYSTEMWIDE+DATABASE_TYPE, IDENTITY_GENERATOR_TAG);
}
return pkTags;
}
public String getHibernateDataType(UMLClass klass, UMLAttribute attr) throws GenerationException
{
log.debug("getHibernateDataType for klass: " + klass.getName() + ", attr: " + attr.getName());
String fqcn = getFQCN(klass);
UMLClass table = getTable(klass);
UMLAttribute col = getMappedColumn(table,fqcn+"."+attr.getName());
Boolean isClob = "CLOB".equalsIgnoreCase(getTagValue(col.getTaggedValues(),TV_TYPE, 1));
UMLDatatype dataType = attr.getDatatype();
String name = dataType.getName();
if(dataType instanceof UMLClass)
name = getFQCN((UMLClass)dataType);
if(name.startsWith("java.lang."))
name = name.substring("java.lang.".length());
if(isClob && "string".equalsIgnoreCase(name))
return "text";
if(isClob && !"string".equalsIgnoreCase(name))
throw new GenerationException("Can not map CLOB to anything other than String");
if("byte[]".equalsIgnoreCase(name))
return "org.springframework.orm.hibernate3.support.BlobByteArrayType";
if("int".equalsIgnoreCase(name) || "integer".equalsIgnoreCase(name))
return "integer";
if("double".equalsIgnoreCase(name))
return "double";
if("float".equalsIgnoreCase(name))
return "float";
if("long".equalsIgnoreCase(name))
return "long";
if("string".equalsIgnoreCase(name))
return "string";
if("char".equalsIgnoreCase(name) || "character".equalsIgnoreCase(name))
return "character";
if("boolean".equalsIgnoreCase(name) )
return "boolean";
if("byte".equalsIgnoreCase(name) )
return "byte";
if("short".equalsIgnoreCase(name) )
return "short";
if("date".equalsIgnoreCase(name) || "java.util.date".equalsIgnoreCase(name))
return "java.util.Date";
if(isISO21090Enabled)
{
if(name.startsWith(ISO_ROOT_PACKAGE_NAME+"."))
name = name.substring((ISO_ROOT_PACKAGE_NAME+".").length());
if("II".equals(name))
return "gov.nih.nci.iso21090.hibernate.usertype.IiUserType";
}
//log.info("Type = "+name);
return name;
}
public String getGetterMethodName(UMLAttribute attr)
{
String name = attr.getName();
return "get"+name.substring(0,1).toUpperCase()+name.substring(1,name.length());
}
public String getSetterMethodName(UMLAttribute attr)
{
String name = attr.getName();
return "set"+name.substring(0,1).toUpperCase()+name.substring(1,name.length());
}
public UMLAssociationEnd getThisEnd(UMLClass klass, List<UMLAssociationEnd>assocEnds) throws GenerationException
{
UMLAssociationEnd end1 = assocEnds.get(0);
UMLAssociationEnd end2 = assocEnds.get(1);
if(end1.getUMLElement().equals(klass))
return end1;
else if(end2.getUMLElement().equals(klass))
return end2;
else
throw new GenerationException("Could not figureout this end");
}
public UMLAssociationEnd getOtherEnd(UMLClass klass, List<UMLAssociationEnd>assocEnds) throws GenerationException
{
UMLAssociationEnd end1 = assocEnds.get(0);
UMLAssociationEnd end2 = assocEnds.get(1);
if(end1.getUMLElement().equals(klass))
return end2;
else if(end2.getUMLElement().equals(klass))
return end1;
else
throw new GenerationException("Could not figureout other end" );
}
public Boolean isAssociationEndMany(UMLAssociationEnd assocEnd)
{
if((assocEnd.getHighMultiplicity()<0)||(assocEnd.getLowMultiplicity()<0))
return true;
else
return false;
}
public Boolean isImplicitParent(UMLAssociationEnd assocEnd)
{
return isImplicitParent((UMLClass)assocEnd.getUMLElement());
}
public String getGetterMethodName(UMLAssociationEnd assocEnd)
{
String name = assocEnd.getRoleName();
return "get"+name.substring(0,1).toUpperCase()+name.substring(1,name.length());
}
public String getSetterMethodName(UMLAssociationEnd assocEnd)
{
String name = assocEnd.getRoleName();
return "set"+name.substring(0,1).toUpperCase()+name.substring(1,name.length());
}
public Boolean isSelfAssociation(UMLAssociationEnd assocEnd1,UMLAssociationEnd assocEnd2)
{
return assocEnd1.getUMLElement().equals(assocEnd2.getUMLElement());
}
public String getClassIdGetterMthod(UMLClass klass) throws GenerationException
{
String idAttrName = getClassIdAttrName(klass);
if (idAttrName == null) return null;
return "get"+firstCharUpper(getClassIdAttrName(klass));
}
private String firstCharUpper(String data)
{
if(data == null || data.length() == 0) return data;
return Character.toUpperCase(data.charAt(0)) + data.substring(1);
}
public String getClassIdAttrName(UMLClass klass) throws GenerationException
{
UMLAttribute idAttr = getClassIdAttr(klass);
if (idAttr == null) return null;
return getClassIdAttr(klass).getName();
}
public UMLAttribute getClassIdAttr(UMLClass klass) throws GenerationException
{
String fqcn = getFQCN(klass);
UMLAttribute idAttr = getColumn(klass,TV_ID_ATTR_COLUMN, fqcn,true,0,1);
if(idAttr !=null) return idAttr;
String idAttrName = "id";
for(UMLAttribute attribute:klass.getAttributes())
if(idAttrName.equals(attribute.getName()))
return attribute;
for(UMLGeneralization gen: klass.getGeneralizations())
{
if(gen.getSubtype() == klass && gen.getSupertype() != klass)
{
UMLAttribute superId = getClassIdAttr((UMLClass)gen.getSupertype());
if(superId != null)
return superId;
}
}
return null;
//throw new GenerationException("No attribute found that maps to the primary key identifier for class : "+fqcn);
}
public Boolean isCollection(UMLClass klass, UMLAttribute attr ) throws GenerationException
{
if(getDataType(attr).startsWith("Collection"))
return true;
return false;
}
public boolean isStatic(UMLAttribute att){
UMLTaggedValue tValue = att.getTaggedValue("static");
if (tValue == null) {
return false;
}
log.debug("UMLAttribute 'static' Tagged Value: " + tValue.getValue());
return ("1".equalsIgnoreCase(tValue.getValue()));
}
public boolean isAbstract(UMLClass klass){
return klass.getAbstractModifier().isAbstract();
}
public String getType(UMLAssociationEnd assocEnd){
UMLTaggedValue tValue = assocEnd.getTaggedValue("type");
if (tValue == null) {
return "";
}
log.debug("UMLAttribute Type Tagged Value: " + tValue.getValue());
return tValue.getValue();
}
public UMLAssociationEnd getOtherAssociationEnd(UMLAssociationEnd assocEnd) {
UMLAssociationEnd otherAssocEnd = null;
for (Iterator i = assocEnd.getOwningAssociation().getAssociationEnds().iterator(); i
.hasNext();) {
UMLAssociationEnd ae = (UMLAssociationEnd) i.next();
if (ae != assocEnd) {
otherAssocEnd = ae;
break;
}
}
return otherAssocEnd;
}
public String getUpperBound(UMLAssociationEnd otherEnd) {
int multiplicity = otherEnd.getHighMultiplicity();
String finalMultiplicity = new String();
if (multiplicity == -1) {
finalMultiplicity = "unbounded";
} else {
Integer x = new Integer(multiplicity);
finalMultiplicity = x.toString();
}
return finalMultiplicity;
}
public String getLowerBound(UMLAssociationEnd otherEnd) {
int multiplicity = otherEnd.getLowMultiplicity();
String finalMultiplicity = new String();
if (multiplicity == -1) {
finalMultiplicity = "unbounded";
} else {
Integer x = new Integer(multiplicity);
finalMultiplicity = x.toString();
}
return finalMultiplicity;
}
public String getMultiplicityValue(UMLAssociationEnd assocEnd){
Element element = ((UMLAssociationEndBean)assocEnd).getJDomElement();
org.jdom.Attribute multAtt = element.getAttribute("multiplicity");
//log.debug("associationEnd: " + assocEnd.getRoleName() + "; multiplicity: " + multAtt.getValue());
if (multAtt!=null)
return multAtt.getValue();
int low = assocEnd.getLowMultiplicity();
int high = assocEnd.getHighMultiplicity();
if(low <0 && high<0)
return "";
if(low >=0 && high>=0)
return low+".."+high;
if(low<0)
return high+"";
return low+"";
}
public boolean isMultiplicityValid(UMLAssociationEnd assocEnd){
String multValue = getMultiplicityValue(assocEnd);
if(multValue == null || "".equalsIgnoreCase(multValue) || multValue.startsWith(".") || multValue.endsWith("."))
return false;
return true;
}
/**
* @param thisEnd
* @param otherEnd
* @return
*/
public boolean isMany2One(UMLAssociationEnd thisEnd, UMLAssociationEnd otherEnd) {
return isAssociationEndMany(thisEnd) && !isAssociationEndMany(otherEnd);
}
/**
* @param thisEnd
* @param otherEnd
* @return
*/
public boolean isAny(UMLAssociationEnd thisEnd,UMLAssociationEnd otherEnd) {
return isAssociationEndMany(thisEnd) && !isAssociationEndMany(otherEnd) && isImplicitParent(otherEnd);
}
/**
* @param thisEnd
* @param otherEnd
* @return
*/
public boolean isOne2Many(UMLAssociationEnd thisEnd,UMLAssociationEnd otherEnd) {
return !isAssociationEndMany(thisEnd) && isAssociationEndMany(otherEnd);
}
/**
* @param thisEnd
* @param otherEnd
* @return
*/
public boolean isMany2Many(UMLAssociationEnd thisEnd,UMLAssociationEnd otherEnd) {
return isAssociationEndMany(thisEnd) && isAssociationEndMany(otherEnd);
}
/**
* @param thisEnd
* @param otherEnd
* @return
*/
public boolean isMany2Any(UMLAssociationEnd thisEnd,UMLAssociationEnd otherEnd) {
return isAssociationEndMany(thisEnd) && isAssociationEndMany(otherEnd) && isImplicitParent(otherEnd);
}
/**
* @param thisEnd
* @param otherEnd
* @return
*/
public boolean isOne2One(UMLAssociationEnd thisEnd,UMLAssociationEnd otherEnd) {
return !isAssociationEndMany(thisEnd) && !isAssociationEndMany(otherEnd);
}
public Collection getAssociationEnds(UMLClass klass) {
return getAssociationEnds(klass, false);
}
public Collection getAssociationEnds(UMLClass klass,
boolean includeInherited) {
log.debug("class = " + klass.getName() + ", includeInherited = "
+ includeInherited);
List<UMLAssociationEnd> assocEndsList = new ArrayList<UMLAssociationEnd>();
UMLClass superClass = klass;
while (superClass != null) {
Collection assocs = superClass.getAssociations();
log.debug( superClass.getName() + " association collection size(): " + assocs.size());
for (Iterator i = assocs.iterator(); i.hasNext();) {
UMLAssociation assoc = (UMLAssociation) i.next();
for (UMLAssociationEnd ae:assoc.getAssociationEnds()){
UMLAssociationEnd otherEnd = getOtherAssociationEnd(ae);
String id = ((UMLClass)(otherEnd.getUMLElement())).getName() + Constant.LEFT_BRACKET
+ getFQCN((UMLClass)(otherEnd.getUMLElement())) + Constant.RIGHT_BRACKET;
log.debug("id (otherEnd): " + id);
log.debug("superClass: " + superClass.getName());
if ((UMLClass)ae.getUMLElement() == superClass) {
log.debug("adding association: " + id + " for class " + superClass.getName());
assocEndsList.add(ae);
}
}
}
if (includeInherited) {
// TODO :: Implement includeInherited
// Collection gens = superClass.getGeneralization();
// if (gens.size() > 0) {
// superClass = (Classifier) ((Generalization) gens.iterator()
// .next()).getParent();
// } else {
// superClass = null;
log.debug("Need to implement includeInherited");
} else {
superClass = null;
}
}
return assocEndsList;
}
public void collectPackages(Collection<UMLPackage> nextLevelPackages, Hashtable<String, Collection<UMLClass>> pkgColl) throws GenerationException
{
for(UMLPackage pkg:nextLevelPackages){
if (isIncluded(pkg)){
String pkgName=getFullPackageName(pkg);
log.debug("including package: " + pkgName);
Collection<UMLClass> pkgClasses = pkg.getClasses();
if (pkgClasses != null && pkgClasses.size() > 0){
for (UMLClass klass:pkgClasses){
if(!STEREO_TYPE_TABLE.equalsIgnoreCase(klass.getStereotype()) && isIncluded(klass)) {
if(!pkgColl.containsKey(pkgName)) {
List<UMLClass> classes = new ArrayList<UMLClass>();
classes.add(klass);
pkgColl.put(pkgName, classes);
} else {
Collection<UMLClass> existingCollection = pkgColl.get(pkgName);
existingCollection.add(klass);
}
}
}
}
} else{
log.debug("excluding package: " + pkg.getName());
}
collectPackages(pkg.getPackages(), pkgColl);
}
}
public void collectPackages(Collection<UMLClass> allClasses, Hashtable<String, Collection<UMLClass>> pkgColl,String defaultNamespacePrefix)
throws GenerationException {
String pkgName=null;
String pkgNamespace=null;
for(UMLClass klass:allClasses){
pkgName = getGMEPackageName(klass);
if (pkgName == null)
pkgName=getFullPackageName(klass);
log.debug("processing klass: " + klass.getName() + " of package " + pkgName);
if (isNamespaceIncluded(klass,defaultNamespacePrefix)){
log.debug("including package: " + pkgName);
if(!STEREO_TYPE_TABLE.equalsIgnoreCase(klass.getStereotype()) && isIncluded(klass)) { //No longer using GME ClassName; e.g., no longer using isIncluded(pkgName+"."+getClassName(klass))) {
pkgNamespace=getGMENamespace(klass);
if (pkgNamespace !=null && (pkgNamespace.endsWith("/") || !pkgNamespace.endsWith(pkgName)))
pkgNamespace=pkgNamespace+pkgName;
log.debug("pkgNamespace: " + pkgNamespace);
if(!pkgColl.containsKey(pkgNamespace)) {
List<UMLClass> classes = new ArrayList<UMLClass>();
classes.add(klass);
pkgColl.put(pkgNamespace, classes);
} else {
Collection<UMLClass> existingCollection = pkgColl.get(pkgNamespace);
existingCollection.add(klass);
}
}
} else{
log.debug("excluding class: " +klass.getName()+" with package: " + pkgName);
}
}
}
public String getGMEPackageName(UMLClass klass) throws GenerationException{
String namespacePkgName = null;
try {
namespacePkgName = getNamespacePackageName(klass);
if (namespacePkgName!=null && namespacePkgName.length()>0)
return namespacePkgName;
} catch(GenerationException ge) {
log.error("ERROR: ", ge);
throw new GenerationException("Error getting the GME package name for: " + getFQEN(klass), ge);
}
namespacePkgName=getGMEPackageName(klass.getPackage());
if (namespacePkgName!=null && namespacePkgName.length()>0)
return namespacePkgName;
log.debug("GME Package name not found for: "+getFullPackageName(klass)+". Returning null");
return null;
}
public String getGMEPackageName(UMLPackage pkg) throws GenerationException{
if (pkg==null)
return null;
log.debug("Getting Package Name for: " +pkg.getName());
String namespacePkgName = getNamespacePackageName(pkg);
if (namespacePkgName!=null && namespacePkgName.length()>0)
return namespacePkgName;
return getGMEPackageName(pkg.getParent());
}
private String getClassName(UMLClass klass)throws GenerationException{
try {
String klassName = getXMLClassName(klass);
if (klassName!=null)
return klassName;
} catch(GenerationException ge) {
log.error("ERROR: ", ge);
throw new GenerationException("Error getting the GME Class (XML Element) name for klass: " + getFQCN(klass));
}
return klass.getName();
}
/**
* Returns all the classes (not the tables) in the XMI file which do not belong to java.lang or java.util package
* @param model
* @return
*/
public Collection<UMLClass> getAllClasses(UMLModel model) throws GenerationException
{
Collection<UMLClass> classes = null;
try {
classes = new HashSet<UMLClass>();
getAllClasses(model.getPackages(),classes);
} catch(Exception e){
log.error("Unable to retrieve classes from model: ", e);
throw new GenerationException("Unable to retrieve classes from model: ", e);
}
return classes;
}
private void getAllClasses(Collection<UMLPackage> pkgCollection,Collection<UMLClass> classes)throws GenerationException
{
for(UMLPackage pkg:pkgCollection)
getAllClasses(pkg,classes);
}
private void getAllClasses(UMLPackage rootPkg,Collection<UMLClass> classes) throws GenerationException
{
if(isIncluded(rootPkg))
{
for(UMLClass klass:rootPkg.getClasses())
{
if(!STEREO_TYPE_TABLE.equalsIgnoreCase(klass.getStereotype()) && isIncluded(klass))
classes.add(klass);
}
}
getAllClasses(rootPkg.getPackages(),classes);
}
/**
* Returns all the interfaces in the XMI file which do not belong to java.lang or java.util package
* @param model
* @return
*/
public Collection<UMLInterface> getAllInterfaces(UMLModel model) throws GenerationException
{
Collection<UMLInterface> interfaces = null;
try {
interfaces = new HashSet<UMLInterface>();
getAllInterfaces(model.getPackages(),interfaces);
} catch(Exception e){
log.error("Unable to retrieve interfaces from model: ", e);
throw new GenerationException("Unable to retrieve interfaces from model: ", e);
}
return interfaces;
}
private void getAllInterfaces(Collection<UMLPackage> pkgCollection,Collection<UMLInterface> interfaces)throws GenerationException
{
for(UMLPackage pkg:pkgCollection)
getAllInterfaces(pkg,interfaces);
}
private void getAllInterfaces(UMLPackage rootPkg,Collection<UMLInterface> interfaces) throws GenerationException
{
if(isIncluded(rootPkg))
{
for(UMLInterface interfaze:rootPkg.getInterfaces())
{
if(!STEREO_TYPE_TABLE.equalsIgnoreCase(interfaze.getStereotype()) && isIncluded(interfaze))
interfaces.add(interfaze);
}
}
getAllInterfaces(rootPkg.getPackages(),interfaces);
}
public Collection<UMLClass> getAllHibernateClasses(UMLModel model) throws GenerationException
{
Collection<UMLClass> allHibernateClasses = getAllParentClasses(model);
allHibernateClasses.addAll(getAllImplicitParentLeafClasses(model));
return allHibernateClasses;
}
/**
* Returns all the classes (not the tables) in the XMI file which do not belong to java.lang or java.util package.
* The class also have to be the root class in the inheritnace hierarchy to be included in the final list
* @param model
* @return
*/
public Collection<UMLClass> getAllParentClasses(UMLModel model) throws GenerationException
{
Collection<UMLClass> classes = new ArrayList<UMLClass>();
getAllParentClasses(model.getPackages(),classes);
return classes;
}
private void getAllParentClasses(Collection<UMLPackage> pkgCollection,Collection<UMLClass> classes) throws GenerationException
{
for(UMLPackage pkg:pkgCollection)
getAllParentClasses(pkg,classes);
}
private void getAllParentClasses(UMLPackage rootPkg,Collection<UMLClass> classes)throws GenerationException
{
if(isIncluded(rootPkg))
{
for(UMLClass klass:rootPkg.getClasses())
{
if(!STEREO_TYPE_TABLE.equalsIgnoreCase(klass.getStereotype()) && isIncluded(klass) && ModelUtil.getSuperclasses(klass).length == 0 && !isImplicitParent(klass))
classes.add(klass);
}
}
getAllParentClasses(rootPkg.getPackages(),classes);
}
/**
* Returns all the classes (not the tables) in the XMI file which do not belong to java.lang or java.util package.
* The class also has to be an implicit parent (parent class with no table mapping) in the inheritance hierarchy to be included in the final list
* @param model
* @return
*/
public Collection<UMLClass> getAllImplicitParentLeafClasses(UMLModel model) throws GenerationException
{
Collection<UMLClass> classes = new ArrayList<UMLClass>();
getAllImplicitParentLeafClasses(model.getPackages(),classes);
return classes;
}
private void getAllImplicitParentLeafClasses(Collection<UMLPackage> pkgCollection,Collection<UMLClass> classes) throws GenerationException
{
for(UMLPackage pkg:pkgCollection)
getAllImplicitParentLeafClasses(pkg,classes);
}
private void getAllImplicitParentLeafClasses(UMLPackage rootPkg,Collection<UMLClass> classes) throws GenerationException
{
if(isIncluded(rootPkg))
{
for(UMLClass klass:rootPkg.getClasses())
{
try {
if(!STEREO_TYPE_TABLE.equalsIgnoreCase(klass.getStereotype()) && isIncluded(klass) && isImplicitParent(getSuperClass(klass)) && !isImplicitParent(klass))
classes.add(klass);
} catch(GenerationException e){
continue;
}
}
}
getAllImplicitParentLeafClasses(rootPkg.getPackages(),classes);
}
/**
* Retrieves the table corresponding to the Dependency link between class and a table.
* If there are no Dependencies that links the class to table or there is more than
* one Dependency then the method throws an exception
*
* @param klass
* @return
* @throws GenerationException
*/
public UMLClass getTable(UMLClass klass) throws GenerationException
{
Set<UMLDependency> dependencies = klass.getDependencies();
Map<String,UMLClass> clientMap = new HashMap<String,UMLClass>();
int count = 0;
UMLClass result = null;
for(UMLDependency dependency:dependencies)
{
UMLClass client = (UMLClass) dependency.getClient();
log.debug("getTable: klass: " + klass.getName() + "Client stereotype: " +client.getStereotype() + "; dependency stereotype: " + dependency.getStereotype());
if(STEREO_TYPE_TABLE.equalsIgnoreCase(client.getStereotype()) && STEREO_TYPE_DATASOURCE_DEPENDENCY.equalsIgnoreCase(dependency.getStereotype()))
{
log.debug("* * * client.getName(): " + client.getName());
clientMap.put(client.getName(), client);
result = client;
}
}
count = clientMap.size();
if(count!=1){
log.debug("getTable: klass: " +klass.getName()+"; count: " + count);
throw new GenerationException("No table found for : "+getFQCN(klass)+". Make sure the corresponding Data Model table (class) has a 'table' Stereotype assigned, and the Dependency between the Data Model table and Logical Model class has a 'DataSource' Stereotype assigned.");
}
return result;
}
/**
* Determines whether the input class is an implicit superclass. Used
* by the code generator to determine whether an implicit inheritance
* hibernate mapping should be created for the input class
* @param klass
* @return
* @throws GenerationException
*/
public boolean isImplicitParent(UMLClass klass)
{
if (klass != null)
log.debug("isImplicitClass " + klass.getName()+": " + (isSuperclass(klass) && hasNoTableMapping(klass)));
return (isSuperclass(klass) && hasNoTableMapping(klass));
}
public boolean hasImplicitParent(UMLClass klass){
UMLClass superclass = klass;
do {
try {
superclass = getSuperClass(superclass);
if(isImplicitParent(superclass)){
return true;
}
} catch (GenerationException e) {
log.error("ERROR encountered checking if class " +klass.getName() + " has an implicit parent: ", e);
return false;
}
} while (!(superclass==null) && !(superclass.getName().equalsIgnoreCase("java.lang.Object")));
return false;
}
/**
* Determines whether the input class is a superclass
* @param klass
* @return
*/
private boolean isSuperclass(UMLClass klass)
{
boolean isSuperClass = false;
if (klass != null)
for(UMLGeneralization gen:klass.getGeneralizations())
{
if(gen.getSupertype() instanceof UMLClass && ((UMLClass)gen.getSupertype()) == klass)
return true;
}
return isSuperClass;
}
/**
* Determines whether the input class is missing a table mapping
* @param klass
* @return
*/
private boolean hasNoTableMapping(UMLClass klass)
{
try {
getTable(klass);
} catch (GenerationException e){
return true;
}
return false;
}
/**
* Scans the tag values of the association to determine which JOIN table the association is using.
*
* @param association
* @param model
* @param klass
* @return
* @throws GenerationException
*/
public UMLClass findCorrelationTable(UMLAssociation association, UMLModel model, UMLClass klass) throws GenerationException
{
return findCorrelationTable(association, model, klass, true);
}
public UMLClass findCorrelationTable(UMLAssociation association, UMLModel model, UMLClass klass, boolean throwException) throws GenerationException
{
int minReq = throwException ? 1:0;
String tableName = getTagValue(klass, association,TV_CORRELATION_TABLE, null,minReq,1);
if(!throwException && (tableName == null || tableName.length() ==0)) return null;
UMLClass correlationTable = ModelUtil.findClass(model,BASE_PKG_DATA_MODEL+"."+tableName);
if(correlationTable == null) throw new GenerationException("No correlation table found named : \""+tableName+"\"");
return correlationTable;
}
public String getMappedColumnName(UMLClass table, String fullyQualifiedAttrName) throws GenerationException
{
return getColumnName(table,TV_MAPPED_ATTR_COLUMN,fullyQualifiedAttrName,false,1,1);
}
public UMLAttribute getMappedColumn(UMLClass table, String fullyQualifiedAttrName) throws GenerationException
{
return getColumn(table,TV_MAPPED_ATTR_COLUMN,fullyQualifiedAttrName,false,1,1);
}
/**
* @param tgElt The TaggableElement (UMLClass, UMLAttribute)
* @return String containing a concatenation of any, all caDSR
* tag values
*/
public String getCaDSRAnnotationContent(UMLTaggableElement tgElt)
{
String publicID = getTagValue(tgElt, TV_CADSR_PUBLICID);
String version = getTagValue(tgElt, TV_CADSR_VERSION);
if (publicID == null && version == null) {
return null;
}
StringBuilder sb = new StringBuilder();
if (publicID != null)
sb.append(TV_CADSR_PUBLICID).append("=\"").append(publicID).append("\"; ");
if (version != null)
sb.append(TV_CADSR_VERSION).append("=\"").append(version).append("\"");
return sb.toString();
}
public String findAssociatedColumn(UMLClass table,UMLClass klass, UMLAssociationEnd otherEnd, UMLClass assocKlass, UMLAssociationEnd thisEnd, Boolean throwException, Boolean isJoin) throws GenerationException
{
String col1 = getColumnName(table,TV_ASSOC_COLUMN,getFQCN(klass) +"."+ otherEnd.getRoleName(),false,0,1);
String col2 = getColumnName(table,TV_ASSOC_COLUMN,getFQCN(assocKlass) +"."+ thisEnd.getRoleName(),false,0,1);
String col3 = getColumnName(table,TV_INVERSE_ASSOC_COLUMN,getFQCN(assocKlass) +"."+ thisEnd.getRoleName(),false,0,1);
log.debug("***** col1: " + col1 + "; col2: " + col2 + "; col3: " + col3);
if("".equals(col1)) col1=null;
if("".equals(col2)) col2=null;
if("".equals(col3)) col3=null;
if((col1==null && col3==null && isJoin && throwException) || (col1==null && col2==null && !isJoin && throwException)){
log.debug("***** col1: " + col1 + "; col2: " + col2 + "; col3: " + col3);
log.debug("klass: " + klass.getName());
log.debug("assocKlass: " + assocKlass.getName());
log.debug("table: " + table.getName());
log.debug("isJoin: " + isJoin);
log.debug("otherEnd.getRoleName(): " +otherEnd.getRoleName());
log.debug("thisEnd.getRoleName(): " +thisEnd.getRoleName());
throw new GenerationException("Could not determine the column for the association between "+getFQCN(klass)+" and "+getFQCN(assocKlass) +". Check for missing implements-association/inverse-of/correlation-table tag(s), where appropriate");
}
/*if(col1!=null && col2!=null && !col1.equals(col2))
throw new GenerationException("More than one column found for the association between "+getFQCN(klass)+" and "+getFQCN(assocKlass));
if(col1!=null && col3!=null && !col1.equals(col3))
throw new GenerationException("More than one column found for the association between "+getFQCN(klass)+" and "+getFQCN(assocKlass));
if(col2!=null && col3!=null && !col2.equals(col3))
throw new GenerationException("More than one column found for the association between "+getFQCN(klass)+" and "+getFQCN(assocKlass));
*/
if(isJoin)
{
return col1==null ? col3 : col1;
}
else
{
return col1==null ? col2 : col1;
}
/* if(col1!=null) return col1;
else if (col3!=null) return col3;
else return col2;
*/ }
public String findAssociatedColumn(UMLClass table,UMLClass klass, UMLAssociationEnd otherEnd, UMLClass assocKlass, UMLAssociationEnd thisEnd, Boolean isJoin) throws GenerationException
{
return findAssociatedColumn(table,klass, otherEnd, assocKlass, thisEnd, true, isJoin);
}
public String findInverseColumnValue(UMLClass table,UMLClass klass, UMLAssociationEnd thisEnd) throws GenerationException
{
return getColumnName(table,TV_INVERSE_ASSOC_COLUMN,getFQCN(klass) +"."+ thisEnd.getRoleName(),false,0,1);
}
public String findDiscriminatingColumnName(UMLClass klass) throws GenerationException
{
UMLClass superKlass = klass;
UMLClass temp = klass;
while ((temp = getSuperClass(temp))!=null && !isImplicitParent(temp))
superKlass = temp;
UMLClass table = getTable(superKlass);
String fqcn = getFQCN(superKlass);
return getColumnName(table,TV_DISCR_COLUMN,fqcn,false,0,1);
}
public String getDiscriminatorValue(UMLClass klass) throws GenerationException
{
return getTagValue(klass,TV_DISCR_COLUMN,null, 1,1);
}
public String getRootDiscriminatorValue(UMLClass klass) throws GenerationException
{
return getTagValue(klass,TV_DISCR_COLUMN,null,0,1);
}
public String getImplicitDiscriminatorColumn(UMLClass table, UMLClass klass, String roleName) throws GenerationException
{
log.debug("**** getImplicitDiscriminator: table: " + table.getName() +"; klass: " + klass.getName() +"; roleName: " + roleName);
return getColumnName(table,TV_DISCR_COLUMN,getFQCN(klass)+"."+roleName,false,1,1);
}
public String getImplicitIdColumn(UMLClass table, UMLClass klass, String roleName) throws GenerationException
{
return getColumnName(table,TV_ASSOC_COLUMN,getFQCN(klass)+"."+roleName,false,1,1);
}
public boolean isLazyLoad(UMLClass klass, UMLAssociation association) throws GenerationException
{
String temp = getTagValue(klass,association, TV_LAZY_LOAD,null, 0,1);
if (temp != null)
throw new GenerationException("Invalid Tag Value found: The '" + TV_LAZY_LOAD + "' Tag Value which is attached to the association link has been replaced with the '" + TV_NCI_EAGER_LOAD + "' Tag Value. Also, it's value must now conform to the following pattern: "+TV_NCI_EAGER_LOAD+"#<fully qualified class name>.<role name>. The value of the tag continues to be 'yes' or 'no'. Please update your model accordingly" );
return true;
}
private String getTagValue(UMLTaggableElement elt, String key, String value, int minOccurrence, int maxOccurrence) throws GenerationException
{
String result = null;
int count = 0;
for(UMLTaggedValue tv: elt.getTaggedValues())
{
if (key.equals(tv.getName()))
{
String tvValue = tv.getValue();
String[] tvValues = tvValue.split(",");
for(String val:tvValues)
{
if(value==null)
{
count++;
result = val;
}
else if(value.equals(val))
{
count++;
result = val;
}
}
}
}
if(count < minOccurrence || (minOccurrence>0 && (result == null || result.trim().length() == 0))) throw new GenerationException("No value found for "+key+" tag in : "+getFQEN(elt));
if(count > maxOccurrence) throw new GenerationException("More than one value found for "+key+" tag in : "+getFQEN(elt));
return result;
}
public String getTagValue(UMLTaggableElement tgElt, String key)
{
for(UMLTaggedValue tv: tgElt.getTaggedValues())
{
if (key.equals(tv.getName()))
{
return tv.getValue();
}
}
return null;
}
private List<String> getTagValues(UMLTaggableElement tgElt, String key)
{
List<String> tagValues = new ArrayList<String>();
for(UMLTaggedValue tv: tgElt.getTaggedValues())
{
if (key.equals(tv.getName()))
{
log.debug(tv.getName() + ": " + tv.getValue());
tagValues.add(tv.getValue());
}
}
return tagValues;
}
public String getColumnName(UMLClass klass, String key, String value, boolean isValuePrefix, int minOccurrence, int maxOccurrence) throws GenerationException
{
UMLAttribute attr = getColumn(klass,key,value,isValuePrefix,minOccurrence,maxOccurrence);
return (attr==null) ? "" : attr.getName();
}
private UMLAttribute getColumn(UMLClass klass, String key, String value, boolean isValuePrefix, int minOccurrence, int maxOccurrence) throws GenerationException
{
UMLAttribute result = null;
int count = 0;
for(UMLAttribute attr: klass.getAttributes())
{
for(UMLTaggedValue tv: attr.getTaggedValues())
{
if (key.equals(tv.getName()))
{
String tvValue = tv.getValue();
String[] tvValues = tvValue.split(",");
for(String val:tvValues)
{
if(value==null)
{
count++;
result = attr;
}
else if(isValuePrefix && val.startsWith(value))
{
count++;
result = attr;
}
else if(!isValuePrefix && val.equals(value))
{
count++;
result = attr;
}
}
}
}
}
if(count < minOccurrence) throw new GenerationException("No value of "+value+" found for "+key+" tag in class : "+getFQCN(klass));
if(count > maxOccurrence) throw new GenerationException("More than one values found for "+key+" tag in class : "+getFQCN(klass));
return result;
}
public String getTagValue(UMLClass klass, UMLAttribute attribute, String key, String value, Boolean isValuePrefix, int minOccurrence, int maxOccurrence) throws GenerationException
{
String result = null;
int count = 0;
for(UMLTaggedValue tv: attribute.getTaggedValues())
{
log.debug("Processing tv: " + tv.getName());
if (key.equals(tv.getName()))
{
String tvValue = tv.getValue();
log.debug("Key equals tv. TV value is: " + tv.getValue());
String[] tvValues = tvValue.split(",");
for(String val:tvValues)
{
if(value==null)
{
count++;
result = val;
}
else if(isValuePrefix && val.startsWith(value))
{
count++;
result = val;
}
else if(!isValuePrefix && val.equals(value))
{
count++;
result = val;
}
}
}
}
if(count < minOccurrence) throw new GenerationException("No value of "+value+" found for "+key+" tag in class : "+getFQCN(klass));
if(count > maxOccurrence) throw new GenerationException("More than one values found for "+key+" tag in class : "+getFQCN(klass));
return result;
}
private String getTagValue(UMLClass klass, UMLAssociation association, String key, String value, Boolean isValuePrefix, int minOccurrence, int maxOccurrence) throws GenerationException
{
List <UMLAssociationEnd>ends = association.getAssociationEnds();
UMLAssociationEnd thisEnd = getThisEnd(klass, ends);
UMLAssociationEnd otherEnd = getOtherEnd(klass, ends);
String thisClassName = getFQCN(((UMLClass)thisEnd.getUMLElement()));
String otherClassName = getFQCN(((UMLClass)otherEnd.getUMLElement()));
String result = null;
int count = 0;
for(UMLTaggedValue tv: association.getTaggedValues())
{
if (key.equals(tv.getName()))
{
String tvValue = tv.getValue();
String[] tvValues = tvValue.split(",");
for(String val:tvValues)
{
if(value==null)
{
count++;
result = val;
}
else if(isValuePrefix && val.startsWith(value))
{
count++;
result = val;
}
else if(!isValuePrefix && val.equals(value))
{
count++;
result = val;
}
}
}
}
if(count < minOccurrence || (minOccurrence >0 && (result == null || result.trim().length() == 0))) throw new GenerationException("No tag value of "+key+" found for the association between "+thisClassName +" and "+ otherClassName +":"+count+":"+result);
if(count > maxOccurrence) throw new GenerationException("More than the expected maximum number (" + maxOccurrence + ") of tag value occurrences for "+key+" found for the association between "+thisClassName +" and "+ otherClassName);
return result;
}
private String getTagValue(UMLClass klass, UMLAssociation association, String key, String value, int minOccurrence, int maxOccurrence) throws GenerationException
{
return getTagValue(klass, association, key, value,false, minOccurrence, maxOccurrence);
}
public String getTagValue(Collection<UMLTaggedValue> tagValues, String key, int maxOccurrence) throws GenerationException
{
StringBuilder temp = new StringBuilder();
for(int i=0;i<maxOccurrence;i++)
{
String searchKey = i==0 ? key : key + (i+1);
for(UMLTaggedValue tv:tagValues)
{
if(searchKey.equals(tv.getName()))
{
temp.append(tv.getValue());
}
}
}
return temp.toString();
}
private String getJavaDocs(Collection<UMLTaggedValue> tagValues) throws GenerationException
{
String documentation = getTagValue(tagValues, TV_DOCUMENTATION, 8);
String description = getTagValue(tagValues, TV_DESCRIPTION, 8);
String temp = documentation == null || documentation.trim().length()==0 ? description : documentation;
StringBuilder doc = new StringBuilder();
doc.append("/**");
doc.append("\n\t* ").append(temp);
doc.append("\n\t**/");
return doc.toString();
}
public String getJavaDocs(UMLInterface interfaze) throws GenerationException
{
return getJavaDocs(interfaze.getTaggedValues());
}
public String getJavaDocs(UMLClass klass) throws GenerationException
{
return getJavaDocs(klass.getTaggedValues());
}
public String getJavaDocs(UMLAttribute attr) throws GenerationException
{
return getJavaDocs(attr.getTaggedValues());
}
public String getJavaDocs(UMLClass klass, UMLAssociation assoc) throws GenerationException
{
UMLAssociationEnd otherEnd = getOtherEnd(klass, assoc.getAssociationEnds());
StringBuilder doc = new StringBuilder();
doc.append("/**");
doc.append("\n * An associated "+getFQCN(((UMLClass)otherEnd.getUMLElement()))+" object");
if(isAssociationEndMany(otherEnd))
doc.append("'s collection ");
doc.append("\n **/\n");
return doc.toString();
}
public String getGetterMethodJavaDocs(UMLAttribute attr) {
StringBuilder doc = new StringBuilder();
doc.append("/**");
doc.append("\n * Retrieves the value of the "+attr.getName()+" attribute");
doc.append("\n * @return ").append(attr.getName());
doc.append("\n **/\n");
return doc.toString();
}
public String getSetterMethodJavaDocs(UMLAttribute attr) {
StringBuilder doc = new StringBuilder();
doc.append("/**");
doc.append("\n * Sets the value of "+attr.getName()+" attribute");
doc.append("\n **/\n");
return doc.toString();
}
public String getGetterMethodJavaDocs(UMLClass klass, UMLAssociation assoc) throws GenerationException {
UMLAssociationEnd otherEnd = getOtherEnd(klass, assoc.getAssociationEnds());
StringBuilder doc = new StringBuilder();
doc.append("/**");
doc.append("\n * Retrieves the value of the "+otherEnd.getRoleName()+" attribute");
doc.append("\n * @return ").append(otherEnd.getRoleName());
doc.append("\n **/\n");
return doc.toString();
}
public String getSetterMethodJavaDocs(UMLClass klass, UMLAssociation assoc) throws GenerationException {
UMLAssociationEnd otherEnd = getOtherEnd(klass, assoc.getAssociationEnds());
StringBuilder doc = new StringBuilder();
doc.append("/**");
doc.append("\n * Sets the value of "+otherEnd.getRoleName()+" attribute");
doc.append("\n **/\n");
return doc.toString();
}
public String reversePackageName(String s) {
StringTokenizer st = new StringTokenizer(s,".");
Vector<String> myVector = new Vector<String>();
StringBuilder myStringBuilder = new StringBuilder();
while (st.hasMoreTokens()) {
String t = st.nextToken();
myVector.add(t);
}
for (int i = myVector.size(); i>0; i
myStringBuilder.append(myVector.elementAt(i-1));
myStringBuilder.append(Constant.DOT);
}
int length1 = myStringBuilder.length();
String finalString1 = myStringBuilder.substring(0,length1-1);
return finalString1;
}
public String getWSDDServiceValue(Collection<UMLClass> classColl)throws GenerationException{
StringBuilder nn1 = new StringBuilder();
for(UMLClass klass:classColl){
String pkgName = getFullPackageName(klass);
nn1.append(pkgName)
.append(Constant.DOT)
.append(klass.getName())
.append(Constant.COMMA);
}
// remove last Comma
return nn1.substring(0, nn1.length()-1);
}
public UMLClass findCollectionTable(UMLAttribute attr, UMLModel model) throws GenerationException
{
String tableName = getTagValue(attr.getTaggedValues(),TV_MAPPED_COLLECTION_TABLE, 1);
UMLClass collectionTable = ModelUtil.findClass(model,BASE_PKG_DATA_MODEL+"."+tableName);
if(collectionTable == null) throw new GenerationException("No collection table found named : \""+tableName+"\"");
return collectionTable;
}
public String getCollectionKeyColumnName(UMLClass table,UMLClass klass, UMLAttribute attr) throws GenerationException
{
return getColumnName(table,TV_MAPPED_ATTR_COLUMN,getFQCN(klass) +"."+ attr.getName(),false,1,1);
}
public String getCollectionElementColumnName(UMLClass table,UMLClass klass, UMLAttribute attr) throws GenerationException
{
return getColumnName(table,TV_MAPPED_ELEMENT_COLUMN,getFQCN(klass) +"."+ attr.getName(),false,1,1);
}
public String getCollectionElementHibernateType(UMLClass klass, UMLAttribute attr) throws GenerationException
{
String name = getDataType(attr);
if(name.startsWith("Collection<"))
{
name = name.substring("Collection<".length());
name = name.substring(0,name.length()-1);
if("int".equalsIgnoreCase(name) || "integer".equalsIgnoreCase(name))
return "integer";
if("double".equalsIgnoreCase(name))
return "double";
if("float".equalsIgnoreCase(name))
return "float";
if("long".equalsIgnoreCase(name))
return "long";
if("string".equalsIgnoreCase(name))
return "string";
if("char".equalsIgnoreCase(name) || "character".equalsIgnoreCase(name))
return "character";
if("boolean".equalsIgnoreCase(name) )
return "boolean";
if("byte".equalsIgnoreCase(name) )
return "byte";
if("short".equalsIgnoreCase(name) )
return "short";
}
return name;
}
public String getJaxbXmlAttributeAnnotation(UMLClass klass, UMLAttribute attr) throws GenerationException{
String type = this.getDataType(attr);
log.debug("* * * datatype for attribute " + attr.getName()+": " + type);
String collectionType = "";
StringBuffer sb = new StringBuffer();
if (type.startsWith("Collection")){
collectionType = type.substring(type.indexOf("<")+1,type.indexOf(">"));
sb.append(" @XmlElementWrapper(name=\"");
sb.append(attr.getName()).append("\", ");
sb.append("namespace=\"").append(this.getNamespaceUriPrefix() + this.getFullPackageName(klass)).append("\")");
sb.append(" @XmlElement(name=\"");
sb.append(collectionType.toLowerCase()).append("\", ");
sb.append("namespace=\"").append(this.getNamespaceUriPrefix() + this.getFullPackageName(klass)).append("\")");
log.debug("Collection Attribute @XmlElement annotation: "+sb.toString());
return sb.toString();
}
if(isISO21090Enabled){
String isoDatatypeValue = isoDatatypeMap.get(attr.getDatatype().getName());
if (!isJavaDataType(attr)) {
log.debug("* * * Detected attribute " + attr.getName()+" is of ISO Datatype: " + isoDatatypeValue);
sb.append(" @XmlElement(namespace=\"").append(getNamespaceUriPrefix()).append(getFullPackageName(klass)).append("\")");
if(isIvlDataType(attr))
{
String ivlDataType = getIvlDataType(attr);
if("PQ".equals(ivlDataType))
sb.append(" @XmlJavaTypeAdapter(JAXBISOIvlPqAdapter.class)");
else if("REAL".equals(ivlDataType))
sb.append(" @XmlJavaTypeAdapter(JAXBISOIvlRealAdapter.class)");
else if("TS".equals(ivlDataType))
sb.append(" @XmlJavaTypeAdapter(JAXBISOIvlTsAdapter.class)");
else if("INT".equals(ivlDataType))
sb.append(" @XmlJavaTypeAdapter(JAXBISOIvlIntAdapter.class)");
else
throw new GenerationException("Invalid Ivl type defined: " + attr.getDatatype().getName());
}
else
{
sb.append(" @XmlJavaTypeAdapter(JAXBISOAdapter.class)");
}
return sb.toString();
}
}
return " @XmlAttribute";
}
public String getJaxbXmlRootElementAnnotation(UMLClass klass){
StringBuffer sb = new StringBuffer();
sb.append("@XmlRootElement(name=\"");
sb.append(klass.getName()).append("\", ");
sb.append("namespace=\"").append(this.getNamespaceUriPrefix() + this.getFullPackageName(klass)).append("\")");
log.debug("@XmlRootElement annotation for class "+klass.getName()+": "+sb.toString());
return sb.toString();
}
public String getJaxbXmlTypeAnnotation(UMLClass klass){
StringBuffer sb = new StringBuffer("@XmlType(name = \"").append(klass.getName());
sb.append("\", namespace=\"");
sb.append(this.getNamespaceUriPrefix() + this.getFullPackageName(klass));
sb.append("\", propOrder = {");
int counter = 0;
int totalAttrCount = klass.getAttributes().size();
for(UMLAttribute attr:klass.getAttributes()){
counter++;
sb.append("\"").append(attr.getName()).append("\"");
if (counter < totalAttrCount){
sb.append(", ");
}
}
counter = 0;
int totalAssocCount = klass.getAssociations().size();
if ((totalAttrCount > 0) && (totalAssocCount > 0)){
sb.append(", ");
}
for(UMLAssociation assoc:klass.getAssociations()){
List<UMLAssociationEnd> assocEnds = assoc.getAssociationEnds();
try {
UMLAssociationEnd otherEnd = this.getOtherEnd(klass,assocEnds);
counter++;
if(otherEnd.isNavigable())
{
sb.append("\"").append(otherEnd.getRoleName()).append("\"");
if (counter < totalAssocCount){
sb.append(", ");
}
}
} catch (GenerationException e) {
log.error("Error generating XML Type Property order for association role name: "+assoc.getRoleName(),e);
}
}
char c = sb.charAt(sb.length()-2);
log.debug("Last propOrder char: " +c);
if ( c==',' ){
sb.deleteCharAt(sb.length()-2);
}
sb.append("})");
log.debug("@XMLType string for class " + klass.getName() + sb.toString() );
return sb.toString();
}
public String getJaxbXmlAccessorTypeAnnotation(){
return "@XmlAccessorType(XmlAccessType.NONE)";
}
public String getJaxbOnCycleDetectedMethod() {
StringBuffer sb = new StringBuffer(" public Object onCycleDetected(Context arg0) {\n");
sb.append(" return null;\n");
sb.append(" }\n");
return sb.toString();
}
public String getJaxbXmlSeeAlsoAnnotation(UMLClass klass){
List<UMLClass> subClasses = getNonImplicitSubclasses(klass);
List<UMLClass> superClasses = getNonImplicitSuperclasses(klass);
StringBuffer sb = new StringBuffer();
boolean found = false;
if (!subClasses.isEmpty()){
int counter = 0;
int totalCount = subClasses.size();
for (UMLClass subKlass:subClasses){
counter++;
found = true;
sb.append(getFullPackageName(subKlass)+"."+subKlass.getName()+".class");
if (counter < totalCount){
sb.append(", ");
}
}
}
if (!superClasses.isEmpty()){
int counter = 0;
int totalCount = superClasses.size();
if(found)
sb.append(",");
for (UMLClass superKlass:superClasses){
counter++;
found = true;
sb.append(getFullPackageName(superKlass)+"."+superKlass.getName()+".class");
if (counter < totalCount){
sb.append(", ");
}
}
}
if(found)
{
StringBuffer sbreturn = new StringBuffer("@XmlSeeAlso({");
sbreturn.append(sb.toString());
sbreturn.append("})");
log.debug("@XMLSeeAlso string for class " + klass.getName() + sb.toString() );
return sbreturn.toString();
}
return "";
}
public List<UMLClass> getNonImplicitSuperclasses(UMLClass implicitKlass){
ArrayList<UMLClass> nonImplicitSuperclasses = new ArrayList<UMLClass>();
getNonImplicitSuperclasses(implicitKlass, nonImplicitSuperclasses);
return nonImplicitSuperclasses;
}
private void getNonImplicitSuperclasses(UMLClass klass, ArrayList<UMLClass> nonImplicitSuperclasses){
for(UMLGeneralization gen:klass.getGeneralizations()){
UMLClass superKlass = (UMLClass)gen.getSupertype();
if(superKlass!=klass && isSuperclass(superKlass)){
if(!nonImplicitSuperclasses.contains(superKlass)){
nonImplicitSuperclasses.add(superKlass);
}
}
if(superKlass!=klass)
getNonImplicitSuperclasses(superKlass, nonImplicitSuperclasses);
}
}
public List<UMLClass> getNonImplicitSubclasses(UMLClass implicitKlass){
ArrayList<UMLClass> nonImplicitSubclasses = new ArrayList<UMLClass>();
getNonImplicitSubclasses(implicitKlass, nonImplicitSubclasses);
return nonImplicitSubclasses;
}
private void getNonImplicitSubclasses(UMLClass klass, ArrayList<UMLClass> nonImplicitSubclasses){
for(UMLGeneralization gen:klass.getGeneralizations()){
UMLClass subKlass = (UMLClass)gen.getSubtype();
if(subKlass!=klass && !isImplicitParent(subKlass)){
nonImplicitSubclasses.add(subKlass);
}
if(subKlass!=klass)
getNonImplicitSubclasses(subKlass, nonImplicitSubclasses);
}
}
/**
* Scans the tag values of the association to determine the cascade-style
*
* @param association
* @param model
* @param klass
* @return
* @throws GenerationException
*/
public String findCascadeStyle(UMLClass klass, String roleName, UMLAssociation association) throws GenerationException
{
for (String cascadeStyles : getTagValues(association, TV_NCI_CASCADE_ASSOCIATION + "#" + getFQCN(klass)+"."+roleName)){
List<String> validCascadeStyles = new ArrayList<String>();
for(String cascadeStyle:cascadeStyles.split(",")){
validCascadeStyles.add(cascadeStyle.trim());
}
StringBuilder validCascadeStyleSB = new StringBuilder();
validCascadeStyleSB.append(validCascadeStyles.get(0));
for (int i = 1; i <validCascadeStyles.size(); i++ ){
validCascadeStyleSB.append(",").append(validCascadeStyles.get(i));
}
return validCascadeStyleSB.toString();
}
return "none";
}
public String isFKAttributeNull(UMLAssociationEnd otherEnd) {
if (otherEnd.getLowMultiplicity() == 0) {
return "false";
}
return "true";
}
/**
* Scans the tag values of the association to determine the cascade-style
*
* @param klass
* @param roleName
* @param association
* @return
* @throws GenerationException
*/
public boolean isLazyLoad(UMLClass klass, String roleName, UMLAssociation association) throws GenerationException
{
for( String eagerLoadValue : getTagValues(association, TV_NCI_EAGER_LOAD + "#" +getFQCN(klass)+"."+roleName)){
if ("true".equalsIgnoreCase(eagerLoadValue) || "yes".equalsIgnoreCase(eagerLoadValue) ){
return false;
}
}
return true;
}
/**
* Scans the tag values of the association to determine the cascade-style
*
* @param association
* @param model
* @param klass
* @return
* @throws GenerationException
*/
public Map<String,String> getValidCascadeStyles(){
return CASCADE_STYLES;
}
/**
* Scans the tag values of the association to determine whether or not an inverse-of tag
* is present in any of the table columns
*
* @param klass
* @param key
* @return
* @throws GenerationException
*/
public List findInverseSettingColumns(UMLClass klass) throws GenerationException
{
List<String> attrs = new ArrayList<String>();
for(UMLAttribute attr: klass.getAttributes())
{
for(UMLTaggedValue tv: attr.getTaggedValues())
{
if (TV_INVERSE_ASSOC_COLUMN.equals(tv.getName()))
{
attrs.add(attr.getName());
}
}
}
return attrs;
}
public String getHibernateValidatorConstraints(UMLClass klass){
ValidatorClass vClass = vModel.getClass(getFQCN(klass));
ValidatorClass vClassExtension = vModelExtension.getClass(getFQCN(klass));
String constraintAnnotationString="";
if (vClass != null)
constraintAnnotationString = "\t" + vClass.getConstraintAnnotationString()+"\n";
if (vClassExtension != null)
constraintAnnotationString += "\t" + vClassExtension.getConstraintAnnotationString()+"\n";
return constraintAnnotationString;
}
public String getHibernateValidatorConstraints(UMLClass klass,UMLAttribute attr){
ValidatorClass vClass = vModel.getClass(getFQCN(klass));
ValidatorClass vClassExtension = vModelExtension.getClass(getFQCN(klass));
List<String> cadsrConstraintAnnotations=new ArrayList<String>();
List<String> userConstraintAnnotations=new ArrayList<String>();
ValidatorAttribute vAttr=null;
if (vClass != null)
vAttr=vClass.getAttribute(attr.getName());
if (vAttr!=null)
cadsrConstraintAnnotations.addAll(vAttr.getConstraintAnnotations());
ValidatorAttribute vAttrExtension=null;
if (vClassExtension != null)
vAttrExtension=vClassExtension.getAttribute(attr.getName());
if (vAttrExtension!=null)
userConstraintAnnotations.addAll(vAttrExtension.getConstraintAnnotations());
//remove duplicates - user constraints override caDSR constraints
List<String> constraintAnnotations=new ArrayList<String>();
for(String cadsrConstraintAnnotation : cadsrConstraintAnnotations){
String cadsrConstraintPrefix = cadsrConstraintAnnotation.indexOf("(") > 0 ? cadsrConstraintAnnotation.substring(0, cadsrConstraintAnnotation.indexOf("(")) : cadsrConstraintAnnotation;
boolean duplicateConstraint = false;
for(String userConstraintAnnotation : userConstraintAnnotations){
if (userConstraintAnnotation.startsWith(cadsrConstraintPrefix)){
duplicateConstraint = true;
break;
}
}
if (!duplicateConstraint)
constraintAnnotations.add(cadsrConstraintAnnotation);
}
constraintAnnotations.addAll(userConstraintAnnotations);
//Handle special @Patterns scenario
List<String> patternConstraintAnnotations=new ArrayList<String>();
for(String constraintAnnotation : constraintAnnotations){
if (constraintAnnotation.indexOf("Pattern")>0){
patternConstraintAnnotations.add(constraintAnnotation);
}
}
StringBuilder sb;
if (!patternConstraintAnnotations.isEmpty()){
sb = new StringBuilder();
constraintAnnotations.removeAll(patternConstraintAnnotations);
sb.append(patternConstraintAnnotations.remove(0));
for (String patternConstraintAnnotation:patternConstraintAnnotations){
sb.append(",").append(patternConstraintAnnotation);
}
constraintAnnotations.add("@Patterns({"+sb.toString()+"})");
}
sb = new StringBuilder();
for(String constraintAnnotation: constraintAnnotations){
sb.append("\n\t").append(constraintAnnotation);
}
return sb.toString();
}
public Collection<String> getXSDRestrictionValues(UMLClass klass,UMLAttribute attr){
ValidatorClass vClass = vModel.getClass(getFQCN(klass));
ValidatorClass vClassExtension = vModelExtension.getClass(getFQCN(klass));
ArrayList<String> permissibleValues = new ArrayList<String>();
//get user supplied permissible value collection from validator extension file
ValidatorAttribute vAttrExtension=null;
if (vClassExtension != null)
vAttrExtension = vClassExtension.getAttribute(attr.getName());
if (vAttrExtension != null)
permissibleValues.addAll(vAttrExtension.getXSDRestrictionCollection());
//user supplied constraints override caDSR constraints, so only retrieve
//caDSR constraints if user did not supply any constraints
if (permissibleValues.isEmpty()){
ValidatorAttribute vAttr=null;
if (vClass != null)
vAttr = vClass.getAttribute(attr.getName());
if (vAttr != null)
permissibleValues.addAll(vAttr.getXSDRestrictionCollection());
}
return permissibleValues;
}
private Collection<String> getHibernateValidatorConstraintImports(UMLClass klass){
ValidatorClass vClass = vModel.getClass(getFQCN(klass));
ValidatorClass vClassExtension = vModelExtension.getClass(getFQCN(klass));
Collection<String> constraintImports = new HashSet<String>();
if (vClass != null)
constraintImports.addAll(vClass.getConstraintImports());
if (vClassExtension != null)
constraintImports.addAll(vClassExtension.getConstraintImports());
if (constraintImports.contains("org.hibernate.validator.Pattern"))
constraintImports.add("org.hibernate.validator.Patterns");
return constraintImports;
}
public String getNamespace(UMLTaggableElement te) throws GenerationException {
String gmeNamespacePrefix = null;
try {
gmeNamespacePrefix = getTagValue(te,TV_NCI_GME_XML_NAMESPACE,null,0,1);
} catch(GenerationException ge) {
log.error("ERROR: ", ge);
throw new GenerationException("Error getting the GME 'NCI_GME_XML_NAMESPACE' tag value for element", ge);
}
return gmeNamespacePrefix;
}
public String getGMENamespace(UMLClass klass) throws GenerationException{
String gmeNamespace = null;
try {
gmeNamespace = getNamespace(klass);
if (gmeNamespace!=null && gmeNamespace.length()>0)
return gmeNamespace;
} catch(GenerationException ge) {
log.error("ERROR: ", ge);
throw new GenerationException("Error getting the GME namespace for: " + getFQEN(klass), ge);
}
gmeNamespace=getGMENamespace(klass.getPackage());
if (gmeNamespace!=null && gmeNamespace.length()>0)
return gmeNamespace;
log.error("GME Namespace name not found for: "+getFullPackageName(klass)+". Returning null");
return null;
}
public String getGMENamespace(UMLPackage pkg) throws GenerationException{
if (pkg==null)
return null;
log.debug("Getting Package Namespace for: " +pkg.getName());
String gmeNamespace = getNamespace(pkg);
if (gmeNamespace!=null && gmeNamespace.length()>0)
return gmeNamespace;
return getGMENamespace(pkg.getParent());
}
public boolean hasGMEXMLNamespaceTag(UMLTaggableElement te){
try {
getTagValue(te,TV_NCI_GME_XML_NAMESPACE,null,0,0);
} catch (GenerationException e) {
return true;
}
return false;
}
private String getNamespacePackageName(UMLTaggableElement te) throws GenerationException {
String gmeNamespace = null;
try {
gmeNamespace = getTagValue(te,TV_NCI_GME_XML_NAMESPACE,null,0,1);
} catch(GenerationException ge) {
log.error("ERROR: ", ge);
throw new GenerationException("Error getting the GME 'NCI_GME_XML_NAMESPACE' tag value for: " + getFQEN(te), ge);
}
if (gmeNamespace != null && gmeNamespace.lastIndexOf('/')<0)
throw new GenerationException("Invalid GME Namespace found for:" + getFQEN(te)+": "+gmeNamespace);
if (gmeNamespace!=null){
return gmeNamespace.substring(gmeNamespace.lastIndexOf('/')+1, gmeNamespace.length());
}
return null;
}
public String getModelNamespace(UMLModel model, String basePkgLogicalModel) throws GenerationException {
//override codegen.properties NAMESPACE_PREFIX property with GME namespace tag value, if it exists
StringTokenizer tokenizer = new StringTokenizer(basePkgLogicalModel, ".");
UMLPackage pkg=null;
if(tokenizer.hasMoreTokens()){
pkg = model.getPackage(tokenizer.nextToken());
while(pkg!=null && tokenizer.hasMoreTokens()){
pkg = pkg.getPackage(tokenizer.nextToken());
}
}
if (pkg==null){
throw new GenerationException("Error getting the Logical Model package for model: " + pkg.getName()+". Make sure the LOGICAL_MODEL property in codegen.properties file is valid.");
}
if (pkg!=null){
log.debug("* * * pkgName: " + pkg.getName());
try {
String modelNamespacePrefix = this.getNamespace(pkg);
log.debug("* * * modelNamespacePrefix: " + modelNamespacePrefix);
if (modelNamespacePrefix != null) {
if (!modelNamespacePrefix.endsWith("/"))
modelNamespacePrefix=modelNamespacePrefix+"/";
return modelNamespacePrefix.replace(" ", "_");
}
} catch (GenerationException ge) {
log.error("ERROR: ", ge);
throw new GenerationException("Error getting the GME Namespace value for model: " + pkg.getName() + ge.getMessage());
}
}
return null;
}
public String getNamespacePrefix(UMLPackage pkg) throws GenerationException {
String gmeNamespace = null;
try {
gmeNamespace = getTagValue(pkg,TV_NCI_GME_XML_NAMESPACE,null,0,1);
} catch(GenerationException ge) {
log.error("ERROR: ", ge);
throw new GenerationException("Error getting the GME 'NCI_GME_XML_NAMESPACE' tag value for UML package: " + getFullPackageName(pkg), ge);
}
if (gmeNamespace != null && gmeNamespace.lastIndexOf('/')<0)
throw new GenerationException("Invalid GME Namespace found for UML package " + getFullPackageName(pkg)+": "+gmeNamespace);
if (gmeNamespace!=null){
return gmeNamespace.substring(0,gmeNamespace.lastIndexOf('/'));
}
return null;
}
public String getXMLClassName(UMLClass klass) throws GenerationException {
try {
return getTagValue(klass,TV_NCI_GME_XML_ELEMENT,null,0,1);
} catch(GenerationException ge) {
log.error("ERROR: ", ge);
throw new GenerationException("Error getting the GME 'NCI_GME_XML_ELEMENT' tag value for klass: " + klass.getName(), ge);
}
}
public boolean hasGMEXMLClassTag(UMLTaggableElement te){
try {
getTagValue(te,TV_NCI_GME_XML_ELEMENT,null,0,0);
} catch (GenerationException e) {
return true;
}
return false;
}
public String getXMLAttributeName(UMLAttribute attr)throws GenerationException{
try {
String attributeName = getTagValue(attr,TV_NCI_GME_XML_LOC_REF,null,0,1);
if (attributeName !=null && attributeName.length()>0 && (attributeName.startsWith("@")))
attributeName=attributeName.substring(1); //remove leading '@' character
return attributeName;
} catch(GenerationException ge) {
log.error("ERROR: ", ge);
throw new GenerationException("Error getting the GME 'NCI_GME_XML_LOC_REF' tag value for attribute: " + attr.getName(), ge);
}
}
public boolean generateXMLAttributeAsElement(UMLAttribute attr)throws GenerationException{
try {
String attributeName = getTagValue(attr,TV_NCI_GME_XML_LOC_REF,null,0,1);
if (attributeName !=null && attributeName.length()>0 && !(attributeName.startsWith("@")))
return true;
return false;
} catch(GenerationException ge) {
log.error("ERROR: ", ge);
throw new GenerationException("Error getting the GME 'NCI_GME_XML_LOC_REF' tag value for attribute: " + attr.getName(), ge);
}
}
public boolean hasGMEXMLAttributeTag(UMLTaggableElement te){
try {
getTagValue(te,TV_NCI_GME_XML_LOC_REF,null,0,0);
} catch (GenerationException e) {
return true;
}
return false;
}
public String getXMLLocRef(UMLAssociationEnd assocEnd, String klassName)throws GenerationException
{
try {
return getGmeLocRef(assocEnd.getOwningAssociation(),klassName);
} catch(GenerationException ge) {
log.error("ERROR: ", ge);
throw new GenerationException("Error getting the GME 'NCI_GME_SOURCE_XML_LOC_REF' or 'NCI_GME_TARGET_XML_LOC_REF' tag value for association roleName: " + assocEnd.getRoleName(), ge);
}
}
private String getGmeLocRef(UMLAssociation assoc,String klassName) throws GenerationException
{
String tv = getTagValue(assoc,TV_NCI_GME_SOURCE_XML_LOC_REF,null,0,1);
if (tv !=null && tv.endsWith("/"+klassName)){
return tv.substring(0, tv.lastIndexOf('/'));
}
tv = getTagValue(assoc,TV_NCI_GME_TARGET_XML_LOC_REF,null,0,1);
if (tv !=null && tv.endsWith("/"+klassName)){
return tv.substring(0, tv.lastIndexOf('/'));
}
return null;
}
public String getGmeSourceLocRef(UMLAssociation assoc) throws GenerationException
{
return getTagValue(assoc,TV_NCI_GME_SOURCE_XML_LOC_REF,null,0,1);
}
public String getGmeTargetLocRef(UMLAssociation assoc) throws GenerationException
{
return getTagValue(assoc,TV_NCI_GME_TARGET_XML_LOC_REF,null,0,1);
}
public boolean hasGMELocRefTag(UMLTaggableElement te){
try {
getTagValue(te,TV_NCI_GME_SOURCE_XML_LOC_REF,null,0,0);
getTagValue(te,TV_NCI_GME_TARGET_XML_LOC_REF,null,0,0);
} catch (GenerationException e) {
return true;
}
return false;
}
public boolean containsIncludedClass(UMLPackage pkg)
throws GenerationException {
for (UMLClass klass : pkg.getClasses()) {
if (isIncluded(klass) && !STEREO_TYPE_TABLE.equalsIgnoreCase(klass.getStereotype())){
return true;
}
}
return false;
}
public String getNamespaceUriPrefix() {
return namespaceUriPrefix;
}
public boolean isUseGMETags() {
return useGMETags;
}
public boolean isJaxbEnabled() {
return isJaxbEnabled;
}
public boolean isISO21090Enabled() {
return isISO21090Enabled;
}
public boolean isJavaDataType(UMLAttribute attr)
{
String originalType = attr.getDatatype().getName();
if(isISO21090Enabled && isoDatatypeMap.containsKey(originalType))
return false;
return javaDatatypeMap.containsKey(originalType.toLowerCase());
}
public boolean isIvlDataType(UMLAttribute attr)
{
String originalType = attr.getDatatype().getName();
if(originalType.startsWith("IVL"))
return true;
return false;
}
public String getIvlDataType(UMLAttribute attr)
{
String originalType = attr.getDatatype().getName();
return originalType.substring(originalType.indexOf("<")+1, originalType.indexOf(">"));
}
public Collection getSortedByJoinUMLAttribute(UMLClass klass, UMLAttribute idAttribute, UMLClass table) throws GenerationException
{
List<UMLAttribute> noJoinRequired = new ArrayList<UMLAttribute>();
List<UMLAttribute> joinRequired = new ArrayList<UMLAttribute>();
if (klass.getAttributes().size() > 0)
{
for (UMLAttribute attr : klass.getAttributes())
{
if (attr != idAttribute)
{
if (isCollection(null, attr))
{
noJoinRequired.add(attr);
}
else if (isJavaDataType(attr))
{
noJoinRequired.add(attr);
}
else // Start ISO Datatype component
{
IsoDatatypeTransformationHelper isoDatatypeTransformationHelper = new IsoDatatypeTransformationHelper();
isoDatatypeTransformationHelper.setModel(model);
isoDatatypeTransformationHelper.setUtils(this);
RootNode rootNode = isoDatatypeTransformationHelper.getDatatypeNode(klass, attr, table);
if (isoDatatypeTransformationHelper.requiresJoin(rootNode))
joinRequired.add(attr);
else
noJoinRequired.add(attr);
}
}
}
}
List<UMLAssociation> noJoinRequiredAssociation = new ArrayList<UMLAssociation>();
List<UMLAssociation> joinRequiredAssociation = new ArrayList<UMLAssociation>();
for(UMLAssociation association:klass.getAssociations()){
List<UMLAssociationEnd> assocEnds = association.getAssociationEnds();
UMLAssociationEnd thisEnd = getThisEnd(klass,assocEnds);
UMLAssociationEnd otherEnd = getOtherEnd(klass,assocEnds);
if (otherEnd.isNavigable())
{
UMLClass assocKlass = (UMLClass) otherEnd.getUMLElement();
if ((isMany2One(thisEnd, otherEnd) || isOne2One(thisEnd, otherEnd)) && null !=findCorrelationTable(association, model, assocKlass, false))
{
joinRequiredAssociation.add(association);
}
else
{
noJoinRequiredAssociation.add(association);
}
}
}
List result = new ArrayList();
result.addAll(noJoinRequired);
result.addAll(noJoinRequiredAssociation);
result.addAll(joinRequired);
result.addAll(joinRequiredAssociation);
return result;
}
public String getHibernateMappingForIsoAttribute(RootNode rootNode, String prefix) throws GenerationException
{
IsoDatatypeTransformationHelper isoDatatypeTransformationHelper = new IsoDatatypeTransformationHelper();
isoDatatypeTransformationHelper.setModel(model);
isoDatatypeTransformationHelper.setUtils(this);
StringBuffer buffer = isoDatatypeTransformationHelper.convertToHibernateComponent(rootNode, prefix);
return buffer.toString();
}
public String getHibernateClassMappingForIsoAttribute(RootNode rootNode, String prefix) throws GenerationException
{
IsoDatatypeTransformationHelper isoDatatypeTransformationHelper = new IsoDatatypeTransformationHelper();
isoDatatypeTransformationHelper.setModel(model);
isoDatatypeTransformationHelper.setUtils(this);
StringBuffer buffer = isoDatatypeTransformationHelper.convertToHibernateClass(rootNode, prefix);
return buffer.toString();
}
public RootNode getDatatypeNode(UMLClass klass, UMLAttribute attribute, UMLClass table) throws GenerationException
{
IsoDatatypeTransformationHelper isoDatatypeTransformationHelper = new IsoDatatypeTransformationHelper();
isoDatatypeTransformationHelper.setModel(model);
isoDatatypeTransformationHelper.setUtils(this);
RootNode rootNode = isoDatatypeTransformationHelper.getDatatypeNode(klass, attribute, table);
return rootNode;
}
public boolean isSeperateClassMappingRequired(RootNode rootNode)
{
IsoDatatypeTransformationHelper isoDatatypeTransformationHelper = new IsoDatatypeTransformationHelper();
isoDatatypeTransformationHelper.setModel(model);
isoDatatypeTransformationHelper.setUtils(this);
return isoDatatypeTransformationHelper.requiresSeperateClassMapping(rootNode);
}
}
|
// This file is part of Serleena.
// Nicola Mometto, Filippo Sestini, Tobia Tesan, Sebastiano Valle.
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
// all copies or substantial portions of the Software.
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
package com.kyloth.serleena.persistence.sqlite;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;
import java.text.SimpleDateFormat;
/**
* Supporta la creazione e l'apertura del database SQLite utilizzato
* dall'applicazione serleena, secondo quando prescritto dal framework Android.
*
* @author Filippo Sestini <sestini.filippo@gmail.com>
* @version 1.0.0
* @since 2015-05-05
*/
public class SerleenaDatabase extends SQLiteOpenHelper {
public static final String DATABASE_NAME = "serleena.kyloth.db";
public static final String TABLE_EXPERIENCES = "experiences";
public static final String TABLE_TRACKS = "tracks";
public static final String TABLE_TELEMETRIES = "telemetries";
public static final String TABLE_TELEM_EVENTS_HEART_CHECKP =
"telemetry_events_heart_checkp";
public static final String TABLE_TELEM_EVENTS_LOCATION =
"telemetry_events_location";
public static final String TABLE_RASTER_MAPS = "raster_maps";
public static final String TABLE_CONTACTS = "contacts";
public static final String TABLE_WEATHER_FORECASTS = "weather_forecasts";
public static final String TABLE_USER_POINTS = "user_points";
private static final int DATABASE_VERSION = 1;
public static final String EVENT_TYPE_HEARTRATE = "event_heartrate";
public static final String EVENT_TYPE_CHECKPOINT = "event_checkpoint";
public static final SimpleDateFormat DATE_FORMAT =
new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
private static final String CREATE_TABLE_EXPERIENCES =
"CREATE TABLE " + TABLE_EXPERIENCES + "(" +
"experience_id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, " +
"experience_name TEXT NOT NULL)";
private static final String CREATE_TABLE_TRACKS =
"CREATE TABLE " + TABLE_TRACKS + "(" +
"track_id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, " +
"track_name TEXT NOT NULL, " +
"track_experience INTEGER NOT NULL, " +
"FOREIGN KEY(track_experience) REFERENCES experiences(experience_id))";
private static final String CREATE_TABLE_TELEMETRIES =
"CREATE TABLE " + TABLE_TELEMETRIES + "(" +
"telem_id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, " +
"telem_track INTEGER NOT NULL, " +
"FOREIGN KEY(telem_track) REFERENCES tracks(track_id))";
private static final String CREATE_TABLE_TELEM_EVENTS_LOCATION =
"CREATE TABLE " + TABLE_TELEM_EVENTS_LOCATION + "(" +
"eventl_id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, " +
"eventl_timestamp TEXT NOT NULL, " +
"eventl_latitude REAL NOT NULL, " +
"eventl_longitude REAL NOT NULL, " +
"eventl_telem INTEGER NOT NULL, " +
"FOREIGN KEY(eventl_telem) REFERENCES telemetries(telem_id))";
private static final String CREATE_TABLE_TELEM_EVENTS_HEART_CHECKP =
"CREATE TABLE " + TABLE_TELEM_EVENTS_HEART_CHECKP + "(" +
"eventhc_id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, " +
"eventhc_timestamp TEXT NOT NULL, " +
"eventhc_value INTEGER NOT NULL, " +
"eventhc_type TEXT NOT NULL, " +
"eventhc_telem INTEGER NOT NULL, " +
"FOREIGN KEY(eventhc_telem) REFERENCES telemetries(telem_id))";
private static final String CREATE_TABLE_RASTER_MAPS =
"CREATE TABLE " + TABLE_RASTER_MAPS + "(" +
"raster_id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, " +
"raster_path TEXT NOT NULL, " +
"raster_ne_corner_latitude REAL NOT NULL, " +
"raster_ne_corner_longitude REAL NOT NULL, " +
"raster_sw_corner_latitude REAL NOT NULL, " +
"raster_sw_corner_longitude REAL NOT NULL)";
private static final String CREATE_TABLE_CONTACTS =
"CREATE TABLE " + TABLE_CONTACTS + "(" +
"contact_id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, " +
"contact_name TEXT NOT NULL, " +
"contact_value TEXT NOT NULL, " +
"contact_ne_corner_latitude REAL NOT NULL, " +
"contact_ne_corner_longitude REAL NOT NULL, " +
"contact_sw_corner_latitude REAL NOT NULL, " +
"contact_sw_corner_longitude REAL NOT NULL)";
private static final String CREATE_TABLE_WEATHER_FORECASTS =
"CREATE TABLE " + TABLE_WEATHER_FORECASTS + "(" +
"weather_id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, " +
"weather_start INTEGER NOT NULL, " +
"weather_end INTEGER INTEGER NULL, " +
"weather_condition TEXT NOT NULL, " +
"weather_temperature INTEGER NOT NULL, " +
"weather_ne_corner_latitude REAL NOT NULL, " +
"weather_ne_corner_longitude REAL NOT NULL, " +
"weather_sw_corner_latitude REAL NOT NULL, " +
"weather_sw_corner_longitude REAL NOT NULL)";
private static final String CREATE_TABLE_USER_POINTS =
"CREATE TABLE " + TABLE_USER_POINTS + "(" +
"userpoint_id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL," +
"userpoint_x REAL NOT NULL, " +
"userpoint_y REAL NOT NULL, " +
"userpoint_experience INTEGER NOT NULL, " +
"FOREIGN KEY(userpoint_experience) REFERENCES " +
"experiences(experience_id))";
/**
* Crea un oggetto SerleenaDatabase.
*
* @param context Oggetto android.content.Context usato per creare o
* aprire il database.
* @param name Nome del database.
* @param factory Usato per creare cursori.
* @param version Versione del database.
*/
public SerleenaDatabase(Context context, String name, CursorFactory factory,
int version) {
super(context, name, factory, version);
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(CREATE_TABLE_EXPERIENCES);
db.execSQL(CREATE_TABLE_TRACKS);
db.execSQL(CREATE_TABLE_TELEMETRIES);
db.execSQL(CREATE_TABLE_TELEM_EVENTS_HEART_CHECKP);
db.execSQL(CREATE_TABLE_TELEM_EVENTS_LOCATION);
db.execSQL(CREATE_TABLE_RASTER_MAPS);
db.execSQL(CREATE_TABLE_CONTACTS);
db.execSQL(CREATE_TABLE_WEATHER_FORECASTS);
db.execSQL(CREATE_TABLE_USER_POINTS);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_EXPERIENCES);
db.execSQL("DROP TABLE IF EXISTS " + TABLE_TRACKS);
db.execSQL("DROP TABLE IF EXISTS " + TABLE_TELEMETRIES);
db.execSQL("DROP TABLE IF EXISTS " + TABLE_TELEM_EVENTS_HEART_CHECKP);
db.execSQL("DROP TABLE IF EXISTS " + TABLE_TELEM_EVENTS_LOCATION);
db.execSQL("DROP TABLE IF EXISTS " + TABLE_RASTER_MAPS);
db.execSQL("DROP TABLE IF EXISTS " + TABLE_CONTACTS);
db.execSQL("DROP TABLE IF EXISTS " + TABLE_WEATHER_FORECASTS);
db.execSQL("DROP TABLE IF EXISTS " + TABLE_USER_POINTS);
onCreate(db);
}
}
|
package com.ctrip.xpipe.service.sso;
import com.google.common.base.Strings;
import com.google.common.collect.Maps;
import com.ctrip.xpipe.api.config.Config;
import org.springframework.boot.context.embedded.FilterRegistrationBean;
import org.springframework.boot.context.embedded.ServletContextInitializer;
import org.springframework.boot.context.embedded.ServletListenerRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.util.EventListener;
import java.util.Map;
import javax.servlet.Filter;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
/**
* @author lepdou 2016-11-08
*/
@Configuration
public class SSOConfigurations {
public static final String KEY_CAS_REGISTER_SERVER_NAME = "cas.register.server.name";
public static final String KEY_CAS_SERVER_LOGIN_URL = "cas.server.login.url";
public static final String KEY_CAS_SERVER_URL_PREFIX = "cas.server.url.prefix";
public static final String KEY_CLOGGING_SERVER_URL = "clogging.server.url";
public static final String KEY_CLOGGING_SERVER_PORT = "clogging.server.port";
public static final String KEY_CREDIS_SERVER_URL = "credis.server.url";
private Config config = Config.DEFAULT;
@Bean
public ServletListenerRegistrationBean redisAppSettingListener() {
ServletListenerRegistrationBean redisAppSettingListener = new ServletListenerRegistrationBean();
redisAppSettingListener.setListener(listener("org.jasig.cas.client.credis.CRedisAppSettingListner"));
return redisAppSettingListener;
}
@Bean
public ServletListenerRegistrationBean singleSignOutHttpSessionListener() {
ServletListenerRegistrationBean singleSignOutHttpSessionListener = new ServletListenerRegistrationBean();
singleSignOutHttpSessionListener
.setListener(listener("org.jasig.cas.client.session.SingleSignOutHttpSessionListener"));
return singleSignOutHttpSessionListener;
}
@Bean
public FilterRegistrationBean casFilter() {
FilterRegistrationBean singleSignOutFilter = new FilterRegistrationBean();
singleSignOutFilter.setFilter(filter("org.jasig.cas.client.session.SingleSignOutFilter"));
|
package com.ensipoly.match3.activities;
import android.content.Context;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.graphics.drawable.GradientDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.GridLayout;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.style.ForegroundColorSpan;
import android.util.Log;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.ensipoly.match3.R;
import com.ensipoly.match3.fragments.GameMenuFragment;
import com.ensipoly.match3.models.Direction;
import com.ensipoly.match3.models.Grid;
import com.ensipoly.match3.models.Token;
import com.ensipoly.match3.models.events.AddEvent;
import com.ensipoly.match3.models.events.EndEvent;
import com.ensipoly.match3.models.events.EventAcceptor;
import com.ensipoly.match3.models.events.EventVisitor;
import com.ensipoly.match3.models.events.MoveEvent;
import com.ensipoly.match3.models.events.RemoveEvent;
import com.ensipoly.match3.models.events.ScoreEvent;
import com.ensipoly.match3.models.events.SwapEvent;
import com.github.clans.fab.FloatingActionButton;
import com.github.clans.fab.FloatingActionMenu;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Observable;
import java.util.Observer;
import java.util.Queue;
import java.util.concurrent.ConcurrentLinkedQueue;
public class GameActivity extends AppCompatActivity implements Observer, EventVisitor {
private static final String TAG = "GameActivity";
private String SCORE;
private String TURNS;
private String MINSCORE;
private String COMBO;
private TextView scoreTextView;
private TextView turnsTextView;
private TextView minScoreTextView;
private TextView comboTextView;
private Grid grid = null;
private GridLayout gridLayout = null;
private Queue<EventAcceptor> listEvents = new ConcurrentLinkedQueue<>();
private boolean addList;
private int turnsLeft;
private int minScore;
private int score;
private int combo;
private int level;
FloatingActionMenu menu;
private SharedPreferences sharedPref;
private FloatingActionButton joker;
private static final int MAX_LEVELS=4;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_game);
level = getIntent().getIntExtra(GameMenuFragment.LEVEL, 1);
sharedPref = getSharedPreferences(
getString(R.string.preference_file_key), Context.MODE_PRIVATE);
menu = (FloatingActionMenu) findViewById(R.id.fab_menu);
menu.setOnMenuToggleListener(new FloatingActionMenu.OnMenuToggleListener() {
@Override
public void onMenuToggle(boolean opened) {
setClickable(!opened);
if (opened)
findViewById(R.id.overlay).setVisibility(View.VISIBLE);
else
findViewById(R.id.overlay).setVisibility(View.GONE);
}
});
findViewById(R.id.restart).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
menu.close(true);
joker.setVisibility(View.VISIBLE);
joker.setLabelVisibility(View.VISIBLE);
listEvents.clear();
initialize(true);
}
});
findViewById(R.id.quit).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
menu.close(true);
joker.setVisibility(View.VISIBLE);
joker.setLabelVisibility(View.VISIBLE);
listEvents.clear();
onBackPressed();
}
});
joker = (FloatingActionButton) findViewById(R.id.joker);
joker.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
menu.close(true);
listEvents.clear();
initialize(false);
}
});
SCORE = getString(R.string.score);
TURNS = getString(R.string.turns_left);
MINSCORE = getString(R.string.min_score);
COMBO = getString(R.string.combo);
scoreTextView = (TextView) findViewById(R.id.score_text);
minScoreTextView = (TextView) findViewById(R.id.min_score_text);
turnsTextView = (TextView) findViewById(R.id.turns_left_text);
comboTextView = (TextView) findViewById(R.id.combo_text);
initialize(true);
}
@Override
public void onBackPressed() {
if(turnsLeft==0) {
super.onBackPressed();
return;
}
if(menu.isOpened()){
menu.close(true);
return;
}
new AlertDialog.Builder(this)
.setIcon(R.drawable.ic_warning_black_24dp)
.setTitle(getString(R.string.quit_alert_title))
.setMessage(getString(R.string.quit_alert_body))
.setPositiveButton(getString(R.string.quit), new DialogInterface.OnClickListener()
{
@Override
public void onClick(DialogInterface dialog, int which) {
GameActivity.super.onBackPressed();
}
})
.setNegativeButton(getString(R.string.cancel), null)
.show();
}
/**
* Helper functions
**/
private GradientDrawable getDrawable(Token token) {
GradientDrawable shape = new GradientDrawable();
shape.setShape(GradientDrawable.OVAL);
shape.setColor(Color.parseColor(token.toString()));
return shape;
}
private void setClickable(boolean clickable) {
for (int i = 0; i < gridLayout.getChildCount(); i++)
gridLayout.getChildAt(i).setLongClickable(clickable);
}
private int convert(int x, int y) {
return x * grid.getColumnCount() + y;
}
private void initGame() {
combo = 1;
switch (level) {
case 1:
turnsLeft = 6;
minScore = 800;
break;
case 2:
turnsLeft = 10;
minScore = 1200;
break;
case 3:
turnsLeft = 10;
minScore = 1400;
break;
case 4:
turnsLeft = 10;
minScore = 1800;
break;
}
}
private void initGrid() {
try {
grid = new Grid(new BufferedReader(new InputStreamReader(getAssets().open("level" + level + ".data"))));
grid.addObserver(this);
if (gridLayout == null)
gridLayout = (GridLayout) findViewById(R.id.grid);
else
gridLayout.removeAllViews();
gridLayout.setRowCount(grid.getRowCount());
gridLayout.setColumnCount(grid.getColumnCount());
for (int x = 0; x < grid.getRowCount(); x++) {
for (int y = 0; y < grid.getColumnCount(); y++) {
ImageView imageView;
// if it's not recycled, initialize some attributes
imageView = new ImageView(this);
GridLayout.LayoutParams params = new GridLayout.LayoutParams();
params.rowSpec = GridLayout.spec(x, 1.0f);
params.columnSpec = GridLayout.spec(y, 1.0f);
imageView.setLayoutParams(params);
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setAdjustViewBounds(true);
imageView.setPadding(8, 8, 8, 8);
imageView.setImageDrawable(getDrawable(grid.getToken(x, y)));
final int xpos = x;
final int ypos = y;
imageView.setLongClickable(true);
imageView.setOnTouchListener(new View.OnTouchListener() {
private MyGestureDetector mgd = new MyGestureDetector(xpos, ypos);
private GestureDetector gestureDetector = null;
@Override
public boolean onTouch(View view, MotionEvent motionEvent) {
if (gestureDetector == null)
gestureDetector = new GestureDetector(GameActivity.this, mgd);
return gestureDetector.onTouchEvent(motionEvent);
}
});
gridLayout.addView(imageView);
}
}
if (grid.isThereAnyCombinationRemaining())
Log.e(TAG, "There is combination");
else
Log.e(TAG, "There is no combination");
} catch (IOException e) {
e.printStackTrace();
}
}
private void setGreenText(TextView view, String beginning, String inGreen) {
String fullText = beginning + inGreen;
Spannable spannable = new SpannableString(fullText);
spannable.setSpan(new ForegroundColorSpan(Color.parseColor("#76FF03")), beginning.length(), fullText.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
view.setText(spannable, TextView.BufferType.SPANNABLE);
}
private void updateTextViews() {
updateTurnsView();
updateScoreAndComboViews();
}
private void updateTurnsView() {
turnsTextView.setText(TURNS + " " + turnsLeft);
}
private void updateScoreAndComboViews() {
if (score >= minScore)
setGreenText(scoreTextView, SCORE + " ", score + "");
else
scoreTextView.setText(SCORE + " " + score);
if (combo > 1)
setGreenText(comboTextView, COMBO + " ", "x" + combo);
else
comboTextView.setText(COMBO + " x" + combo);
}
private void initialize(int level,boolean resetScore){
this.level = level;
initialize(resetScore);
}
private void initialize(boolean resetScore){
if(resetScore)
score =0;
initGame();
initGrid();
minScoreTextView.setText(MINSCORE + " " + minScore);
((TextView) findViewById(R.id.level_text)).setText(getLevelString());
updateTextViews();
}
private String getLevelString(){
switch (level){
case 1:
return getString(R.string.level1);
case 2:
return getString(R.string.level2);
case 3:
return getString(R.string.level3);
case 4:
return getString(R.string.level4);
default:
return "";
}
}
/**
* Visitor functions
**/
@Override
public void visit(AddEvent add) {
if (addList) {
listEvents.add(add);
} else {
int x = add.getX();
int y = add.getY();
Token token = add.getToken();
ImageView view = ((ImageView) gridLayout.getChildAt(convert(x, y)));
view.setImageDrawable(getDrawable(token));
view.setVisibility(View.VISIBLE);
}
}
@Override
public void visit(RemoveEvent re) {
if (addList) {
listEvents.add(re);
} else {
int x = re.getX();
int y = re.getY();
gridLayout.getChildAt(convert(x, y)).setVisibility(View.INVISIBLE);
}
}
@Override
public void visit(MoveEvent move) {
if (addList) {
listEvents.add(move);
} else {
int prevX = move.getPrevX();
int newX = move.getNewX();
int y = move.getY();
Token prevToken = move.getToken();
ImageView view = ((ImageView) gridLayout.getChildAt(convert(newX, y)));
view.setImageDrawable(getDrawable(prevToken));
view.setVisibility(View.VISIBLE);
gridLayout.getChildAt(convert(prevX, y)).setVisibility(View.INVISIBLE);
}
}
@Override
public void visit(SwapEvent swap) {
if (addList) {
listEvents.add(swap);
} else {
int x1 = swap.getX1();
int y1 = swap.getY1();
int x2 = swap.getX2();
int y2 = swap.getY2();
Token t1 = swap.getT1();
Token t2 = swap.getT2();
ImageView view = ((ImageView) gridLayout.getChildAt(convert(x1, y1)));
view.setImageDrawable(getDrawable(t2));
view = ((ImageView) gridLayout.getChildAt(convert(x2, y2)));
view.setImageDrawable(getDrawable(t1));
}
}
@Override
public void visit(EndEvent end) {
if (addList) {
addList = false;
listEvents.add(end);
doEvents();
} else {
turnsLeft
updateTurnsView();
combo = 1;
updateScoreAndComboViews();
if (end.isEndGame() || turnsLeft == 0) {
menu.open(true);
if(turnsLeft==0) {
joker.setLabelVisibility(View.GONE);
joker.setVisibility(View.GONE);
}
}else
setClickable(true);
if(score>=minScore && level<MAX_LEVELS){
int best= sharedPref.getInt(getString(R.string.best_level),-1);
if(best<0)
Log.e(TAG,"Unexpected best level");
if (best==level){
SharedPreferences.Editor editor = sharedPref.edit();
editor.putInt(getString(R.string.best_level), level+1);
editor.apply();
new AlertDialog.Builder(this)
.setTitle(getString(R.string.unlock_alert_title))
.setMessage(getString(R.string.unlock_alert_body))
.setPositiveButton(getString(R.string.next_level), new DialogInterface.OnClickListener()
{
@Override
public void onClick(DialogInterface dialog, int which) {
initialize(level+1,true);
}
})
.setNegativeButton(getString(R.string.continue_button), null)
.show();
}
}
}
}
@Override
public void visit(ScoreEvent scoreEvent) {
if (addList) {
listEvents.add(scoreEvent);
} else {
score += scoreEvent.getScore();
combo = scoreEvent.getCombo();
updateScoreAndComboViews();
}
}
private void doEvents() {
if (listEvents.size() == 0)
return;
EventAcceptor event = listEvents.poll();
event.accept(this);
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
public void run() {
doEvents();
}
}, 300);
}
/**
* Observer functions
**/
@Override
public void update(Observable observable, Object o) {
if (o instanceof EventAcceptor) {
((EventAcceptor) o).accept(this);
}
}
/**
* Gesture functions
**/
class MyGestureDetector extends GestureDetector.SimpleOnGestureListener {
private static final int SWIPE_MIN_DISTANCE = 120;
private static final int SWIPE_THRESHOLD_VELOCITY = 200;
private int x;
private int y;
MyGestureDetector(int x, int y) {
this.x = x;
this.y = y;
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
Direction dir = null;
// right to left swipe
if (e1.getX() - e2.getX() > SWIPE_MIN_DISTANCE && Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) {
Toast.makeText(GameActivity.this, "Left Swipe", Toast.LENGTH_SHORT).show();
dir = Direction.LEFT;
} else if (e2.getX() - e1.getX() > SWIPE_MIN_DISTANCE && Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) {
Toast.makeText(GameActivity.this, "Right Swipe", Toast.LENGTH_SHORT).show();
dir = Direction.RIGHT;
} else if (e1.getY() - e2.getY() > SWIPE_MIN_DISTANCE && Math.abs(velocityY) > SWIPE_THRESHOLD_VELOCITY) {
Toast.makeText(GameActivity.this, "Up Swipe", Toast.LENGTH_SHORT).show();
dir = Direction.UP;
} else if (e2.getY() - e1.getY() > SWIPE_MIN_DISTANCE && Math.abs(velocityY) > SWIPE_THRESHOLD_VELOCITY) {
Toast.makeText(GameActivity.this, "Down Swipe", Toast.LENGTH_SHORT).show();
dir = Direction.DOWN;
}
if (dir == null)
return false;
if (grid.isSwapPossible(x, y, dir)) {
setClickable(false);
addList = true;
grid.swapElements(x, y, dir);
} else {
Toast.makeText(GameActivity.this, "Swap Impossible", Toast.LENGTH_SHORT).show();
}
return true;
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
}
}
|
package com.ensipoly.match3.activities;
import android.content.Context;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.graphics.drawable.GradientDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.GridLayout;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.style.ForegroundColorSpan;
import android.util.Log;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.ensipoly.match3.R;
import com.ensipoly.match3.fragments.GameMenuFragment;
import com.ensipoly.match3.models.Direction;
import com.ensipoly.match3.models.Grid;
import com.ensipoly.match3.models.Token;
import com.ensipoly.match3.models.events.AddEvent;
import com.ensipoly.match3.models.events.EndEvent;
import com.ensipoly.match3.models.events.EventAcceptor;
import com.ensipoly.match3.models.events.EventVisitor;
import com.ensipoly.match3.models.events.MoveEvent;
import com.ensipoly.match3.models.events.RemoveEvent;
import com.ensipoly.match3.models.events.ScoreEvent;
import com.ensipoly.match3.models.events.SwapEvent;
import com.github.clans.fab.FloatingActionButton;
import com.github.clans.fab.FloatingActionMenu;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Observable;
import java.util.Observer;
import java.util.Queue;
import java.util.concurrent.ConcurrentLinkedQueue;
public class GameActivity extends AppCompatActivity implements Observer, EventVisitor {
private static final String TAG = "GameActivity";
private String SCORE;
private String TURNS;
private String MINSCORE;
private String COMBO;
private TextView scoreTextView;
private TextView turnsTextView;
private TextView minScoreTextView;
private TextView comboTextView;
private Grid grid = null;
private GridLayout gridLayout = null;
private Queue<EventAcceptor> listEvents = new ConcurrentLinkedQueue<>();
private boolean addList;
private int turnsLeft;
private int minScore;
private int score;
private int combo;
private int level;
FloatingActionMenu menu;
private SharedPreferences sharedPref;
private FloatingActionButton joker;
private static final int MAX_LEVELS=4;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_game);
level = getIntent().getIntExtra(GameMenuFragment.LEVEL, 1);
sharedPref = getSharedPreferences(
getString(R.string.preference_file_key), Context.MODE_PRIVATE);
menu = (FloatingActionMenu) findViewById(R.id.fab_menu);
menu.setOnMenuToggleListener(new FloatingActionMenu.OnMenuToggleListener() {
@Override
public void onMenuToggle(boolean opened) {
setClickable(!opened);
if (opened)
findViewById(R.id.overlay).setVisibility(View.VISIBLE);
else
findViewById(R.id.overlay).setVisibility(View.GONE);
}
});
findViewById(R.id.restart).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
menu.close(true);
joker.setVisibility(View.VISIBLE);
joker.setLabelVisibility(View.VISIBLE);
listEvents.clear();
initialize(true);
}
});
findViewById(R.id.quit).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
menu.close(true);
joker.setVisibility(View.VISIBLE);
joker.setLabelVisibility(View.VISIBLE);
listEvents.clear();
quitDialog();
}
});
joker = (FloatingActionButton) findViewById(R.id.joker);
joker.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
menu.close(true);
listEvents.clear();
initialize(false);
}
});
SCORE = getString(R.string.score);
TURNS = getString(R.string.turns_left);
MINSCORE = getString(R.string.min_score);
COMBO = getString(R.string.combo);
scoreTextView = (TextView) findViewById(R.id.score_text);
minScoreTextView = (TextView) findViewById(R.id.min_score_text);
turnsTextView = (TextView) findViewById(R.id.turns_left_text);
comboTextView = (TextView) findViewById(R.id.combo_text);
initialize(true);
}
@Override
public void onBackPressed() {
if(turnsLeft==0) {
super.onBackPressed();
return;
}
if(menu.isOpened()){
menu.close(true);
return;
}
quitDialog();
}
/**
* Helper functions
**/
private GradientDrawable getDrawable(Token token) {
GradientDrawable shape = new GradientDrawable();
shape.setShape(GradientDrawable.OVAL);
shape.setColor(Color.parseColor(token.toString()));
return shape;
}
private void setClickable(boolean clickable) {
for (int i = 0; i < gridLayout.getChildCount(); i++)
gridLayout.getChildAt(i).setLongClickable(clickable);
}
private int convert(int x, int y) {
return x * grid.getColumnCount() + y;
}
private void initGame() {
combo = 1;
switch (level) {
case 1:
turnsLeft = 6;
minScore = 800;
break;
case 2:
turnsLeft = 10;
minScore = 1200;
break;
case 3:
turnsLeft = 10;
minScore = 1400;
break;
case 4:
turnsLeft = 10;
minScore = 1800;
break;
}
}
private void initGrid() {
try {
grid = new Grid(new BufferedReader(new InputStreamReader(getAssets().open("level" + level + ".data"))));
grid.addObserver(this);
if (gridLayout == null)
gridLayout = (GridLayout) findViewById(R.id.grid);
else
gridLayout.removeAllViews();
gridLayout.setRowCount(grid.getRowCount());
gridLayout.setColumnCount(grid.getColumnCount());
for (int x = 0; x < grid.getRowCount(); x++) {
for (int y = 0; y < grid.getColumnCount(); y++) {
ImageView imageView;
// if it's not recycled, initialize some attributes
imageView = new ImageView(this);
GridLayout.LayoutParams params = new GridLayout.LayoutParams();
params.rowSpec = GridLayout.spec(x, 1.0f);
params.columnSpec = GridLayout.spec(y, 1.0f);
imageView.setLayoutParams(params);
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setAdjustViewBounds(true);
imageView.setPadding(8, 8, 8, 8);
imageView.setImageDrawable(getDrawable(grid.getToken(x, y)));
final int xpos = x;
final int ypos = y;
imageView.setLongClickable(true);
imageView.setOnTouchListener(new View.OnTouchListener() {
private MyGestureDetector mgd = new MyGestureDetector(xpos, ypos);
private GestureDetector gestureDetector = null;
@Override
public boolean onTouch(View view, MotionEvent motionEvent) {
if (gestureDetector == null)
gestureDetector = new GestureDetector(GameActivity.this, mgd);
return gestureDetector.onTouchEvent(motionEvent);
}
});
gridLayout.addView(imageView);
}
}
if (grid.isThereAnyCombinationRemaining())
Log.e(TAG, "There is combination");
else
Log.e(TAG, "There is no combination");
} catch (IOException e) {
e.printStackTrace();
}
}
private void setGreenText(TextView view, String beginning, String inGreen) {
String fullText = beginning + inGreen;
Spannable spannable = new SpannableString(fullText);
spannable.setSpan(new ForegroundColorSpan(Color.parseColor("#76FF03")), beginning.length(), fullText.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
view.setText(spannable, TextView.BufferType.SPANNABLE);
}
private void updateTextViews() {
updateTurnsView();
updateScoreAndComboViews();
}
private void updateTurnsView() {
turnsTextView.setText(TURNS + " " + turnsLeft);
}
private void updateScoreAndComboViews() {
if (score >= minScore)
setGreenText(scoreTextView, SCORE + " ", score + "");
else
scoreTextView.setText(SCORE + " " + score);
if (combo > 1)
setGreenText(comboTextView, COMBO + " ", "x" + combo);
else
comboTextView.setText(COMBO + " x" + combo);
}
private void initialize(int level,boolean resetScore){
this.level = level;
initialize(resetScore);
}
private void initialize(boolean resetScore){
if(resetScore)
score =0;
initGame();
initGrid();
minScoreTextView.setText(MINSCORE + " " + minScore);
((TextView) findViewById(R.id.level_text)).setText(getLevelString());
updateTextViews();
}
private String getLevelString(){
switch (level){
case 1:
return getString(R.string.level1);
case 2:
return getString(R.string.level2);
case 3:
return getString(R.string.level3);
case 4:
return getString(R.string.level4);
default:
return "";
}
}
private void quitDialog(){
if(turnsLeft==0) {
super.onBackPressed();
return;
}
new AlertDialog.Builder(this)
.setIcon(R.drawable.ic_warning_black_24dp)
.setTitle(getString(R.string.quit_alert_title))
.setMessage(getString(R.string.quit_alert_body))
.setPositiveButton(getString(R.string.quit), new DialogInterface.OnClickListener()
{
@Override
public void onClick(DialogInterface dialog, int which) {
GameActivity.super.onBackPressed();
}
})
.setNegativeButton(getString(R.string.cancel), null)
.show();
}
/**
* Visitor functions
**/
@Override
public void visit(AddEvent add) {
if (addList) {
listEvents.add(add);
} else {
int x = add.getX();
int y = add.getY();
Token token = add.getToken();
ImageView view = ((ImageView) gridLayout.getChildAt(convert(x, y)));
view.setImageDrawable(getDrawable(token));
view.setVisibility(View.VISIBLE);
}
}
@Override
public void visit(RemoveEvent re) {
if (addList) {
listEvents.add(re);
} else {
int x = re.getX();
int y = re.getY();
gridLayout.getChildAt(convert(x, y)).setVisibility(View.INVISIBLE);
}
}
@Override
public void visit(MoveEvent move) {
if (addList) {
listEvents.add(move);
} else {
int prevX = move.getPrevX();
int newX = move.getNewX();
int y = move.getY();
Token prevToken = move.getToken();
ImageView view = ((ImageView) gridLayout.getChildAt(convert(newX, y)));
view.setImageDrawable(getDrawable(prevToken));
view.setVisibility(View.VISIBLE);
gridLayout.getChildAt(convert(prevX, y)).setVisibility(View.INVISIBLE);
}
}
@Override
public void visit(SwapEvent swap) {
if (addList) {
listEvents.add(swap);
} else {
int x1 = swap.getX1();
int y1 = swap.getY1();
int x2 = swap.getX2();
int y2 = swap.getY2();
Token t1 = swap.getT1();
Token t2 = swap.getT2();
ImageView view = ((ImageView) gridLayout.getChildAt(convert(x1, y1)));
view.setImageDrawable(getDrawable(t2));
view = ((ImageView) gridLayout.getChildAt(convert(x2, y2)));
view.setImageDrawable(getDrawable(t1));
}
}
@Override
public void visit(EndEvent end) {
if (addList) {
addList = false;
listEvents.add(end);
doEvents();
} else {
turnsLeft
updateTurnsView();
combo = 1;
updateScoreAndComboViews();
if (end.isEndGame() || turnsLeft == 0) {
menu.open(true);
if(turnsLeft==0) {
joker.setLabelVisibility(View.GONE);
joker.setVisibility(View.GONE);
}
}else
setClickable(true);
if(score>=minScore && level<MAX_LEVELS){
int best= sharedPref.getInt(getString(R.string.best_level),-1);
if(best<0)
Log.e(TAG,"Unexpected best level");
if (best==level){
SharedPreferences.Editor editor = sharedPref.edit();
editor.putInt(getString(R.string.best_level), level+1);
editor.apply();
new AlertDialog.Builder(this)
.setTitle(getString(R.string.unlock_alert_title))
.setMessage(getString(R.string.unlock_alert_body))
.setPositiveButton(getString(R.string.next_level), new DialogInterface.OnClickListener()
{
@Override
public void onClick(DialogInterface dialog, int which) {
initialize(level+1,true);
}
})
.setNegativeButton(getString(R.string.continue_button), null)
.show();
}
}
}
}
@Override
public void visit(ScoreEvent scoreEvent) {
if (addList) {
listEvents.add(scoreEvent);
} else {
score += scoreEvent.getScore();
combo = scoreEvent.getCombo();
updateScoreAndComboViews();
}
}
private void doEvents() {
if (listEvents.size() == 0)
return;
EventAcceptor event = listEvents.poll();
event.accept(this);
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
public void run() {
doEvents();
}
}, 300);
}
/**
* Observer functions
**/
@Override
public void update(Observable observable, Object o) {
if (o instanceof EventAcceptor) {
((EventAcceptor) o).accept(this);
}
}
/**
* Gesture functions
**/
class MyGestureDetector extends GestureDetector.SimpleOnGestureListener {
private static final int SWIPE_MIN_DISTANCE = 120;
private static final int SWIPE_THRESHOLD_VELOCITY = 200;
private int x;
private int y;
MyGestureDetector(int x, int y) {
this.x = x;
this.y = y;
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
Direction dir = null;
// right to left swipe
if (e1.getX() - e2.getX() > SWIPE_MIN_DISTANCE && Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) {
Toast.makeText(GameActivity.this, "Left Swipe", Toast.LENGTH_SHORT).show();
dir = Direction.LEFT;
} else if (e2.getX() - e1.getX() > SWIPE_MIN_DISTANCE && Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) {
Toast.makeText(GameActivity.this, "Right Swipe", Toast.LENGTH_SHORT).show();
dir = Direction.RIGHT;
} else if (e1.getY() - e2.getY() > SWIPE_MIN_DISTANCE && Math.abs(velocityY) > SWIPE_THRESHOLD_VELOCITY) {
Toast.makeText(GameActivity.this, "Up Swipe", Toast.LENGTH_SHORT).show();
dir = Direction.UP;
} else if (e2.getY() - e1.getY() > SWIPE_MIN_DISTANCE && Math.abs(velocityY) > SWIPE_THRESHOLD_VELOCITY) {
Toast.makeText(GameActivity.this, "Down Swipe", Toast.LENGTH_SHORT).show();
dir = Direction.DOWN;
}
if (dir == null)
return false;
if (grid.isSwapPossible(x, y, dir)) {
setClickable(false);
addList = true;
grid.swapElements(x, y, dir);
} else {
Toast.makeText(GameActivity.this, "Swap Impossible", Toast.LENGTH_SHORT).show();
}
return true;
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
}
}
|
package com.intellij.psi;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.util.Pair;
import com.intellij.psi.util.InheritanceUtil;
import com.intellij.psi.util.PsiUtil;
import com.intellij.psi.util.TypeConversionUtil;
import com.intellij.psi.search.GlobalSearchScope;
import com.intellij.psi.search.PsiSearchHelper;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.Set;
/**
* @author ven
*/
public class GenericsUtil {
private static final Logger LOG = Logger.getInstance("#com.intellij.psi.GenericsUtil");
public static PsiType getGreatestLowerBound(PsiType type1, PsiType type2) {
return PsiIntersectionType.createIntersection(new PsiType[]{type1, type2});
}
public static PsiType getLeastUpperBound(PsiType type1, PsiType type2, PsiManager manager) {
if (type1 instanceof PsiPrimitiveType || type2 instanceof PsiPrimitiveType) return null;
return getLeastUpperBound(type1, type2, new LinkedHashSet<Pair<PsiType, PsiType>>(), manager);
}
private static PsiType getLeastUpperBound(PsiType type1, PsiType type2, Set<Pair<PsiType, PsiType>> compared, PsiManager manager) {
if (type1 instanceof PsiCapturedWildcardType) {
return getLeastUpperBound(((PsiCapturedWildcardType)type1).getUpperBound(), type2, compared, manager);
}
else if (type2 instanceof PsiCapturedWildcardType) {
return getLeastUpperBound(type1, ((PsiCapturedWildcardType)type2).getUpperBound(), compared, manager);
}
if (type1 instanceof PsiArrayType && type2 instanceof PsiArrayType) {
final PsiType componentType = getLeastUpperBound(((PsiArrayType)type1).getComponentType(),
((PsiArrayType)type2).getComponentType(), manager);
if (componentType != null) {
return componentType.createArrayType();
}
}
else if (type1 instanceof PsiClassType && type2 instanceof PsiClassType) {
PsiClassType.ClassResolveResult classResolveResult1 = ((PsiClassType)type1).resolveGenerics();
PsiClassType.ClassResolveResult classResolveResult2 = ((PsiClassType)type2).resolveGenerics();
PsiClass aClass = classResolveResult1.getElement();
PsiClass bClass = classResolveResult2.getElement();
if (aClass == null || bClass == null) {
return manager.getElementFactory().createTypeByFQClassName("java.lang.Object", GlobalSearchScope.allScope(manager.getProject()));
}
PsiClass[] supers = getLeastUpperClasses(aClass, bClass);
if (supers.length == 0) {
return manager.getElementFactory().createTypeByFQClassName("java.lang.Object", aClass.getResolveScope());
}
PsiClassType[] conjuncts = new PsiClassType[supers.length];
for (int i = 0; i < supers.length; i++) {
PsiClass aSuper = supers[i];
PsiSubstitutor subst1 = TypeConversionUtil.getSuperClassSubstitutor(aSuper, aClass,
classResolveResult1.getSubstitutor());
PsiSubstitutor subst2 = TypeConversionUtil.getSuperClassSubstitutor(aSuper, bClass,
classResolveResult2.getSubstitutor());
LOG.assertTrue(subst1 != null && subst2 != null);
Iterator<PsiTypeParameter> iterator = PsiUtil.typeParametersIterator(aSuper);
PsiSubstitutor substitutor = PsiSubstitutor.EMPTY;
while (iterator.hasNext()) {
PsiTypeParameter parameter = iterator.next();
PsiType mapping1 = subst1.substitute(parameter);
PsiType mapping2 = subst2.substitute(parameter);
if (mapping1 != null && mapping2 != null) {
substitutor = substitutor.put(parameter, getLeastContainingTypeArgument(mapping1, mapping2, compared, manager));
}
else {
substitutor = substitutor.put(parameter, null);
}
}
conjuncts[i] = manager.getElementFactory().createType(aSuper, substitutor);
}
return PsiIntersectionType.createIntersection(conjuncts);
}
return manager.getElementFactory().createTypeByFQClassName("java.lang.Object", GlobalSearchScope.allScope(manager.getProject()));
}
private static PsiType getLeastContainingTypeArgument(PsiType type1,
PsiType type2,
Set<Pair<PsiType, PsiType>> compared,
PsiManager manager) {
Pair<PsiType, PsiType> p = new Pair<PsiType, PsiType>(type1, type2);
if (compared.contains(p)) return PsiWildcardType.createUnbounded(manager);
compared.add(p);
if (type1 instanceof PsiWildcardType) {
PsiWildcardType wild1 = (PsiWildcardType)type1;
if (type2 instanceof PsiWildcardType) {
PsiWildcardType wild2 = (PsiWildcardType)type2;
if (wild1.isExtends() == wild2.isExtends()) {
return wild1.isExtends() ? PsiWildcardType.createExtends(manager,
getLeastUpperBound(wild1.getBound(), wild2.getBound(), compared,
manager)) :
wild1.isSuper() ? PsiWildcardType.createSuper(manager, getGreatestLowerBound(wild1.getBound(), wild2.getBound())) :
wild1;
}
else {
return wild1.getBound().equals(wild2.getBound()) ? wild1.getBound() : PsiWildcardType.createUnbounded(manager);
}
}
else {
return wild1.isExtends() ? PsiWildcardType.createExtends(manager, getLeastUpperBound(wild1.getBound(), type2, compared, manager)) :
wild1.isSuper() ? PsiWildcardType.createSuper(manager, getGreatestLowerBound(wild1.getBound(), type2)) :
wild1;
}
}
else if (type2 instanceof PsiWildcardType) {
return getLeastContainingTypeArgument(type2, type1, compared, manager);
}
//Done with wildcards
if (type1.equals(type2)) return type1;
return PsiWildcardType.createExtends(manager, getLeastUpperBound(type1, type2, compared, manager));
}
public static PsiClass[] getLeastUpperClasses(PsiClass aClass, PsiClass bClass) {
if (InheritanceUtil.isInheritorOrSelf(aClass, bClass, true)) return new PsiClass[]{bClass};
Set<PsiClass> supers = new LinkedHashSet<PsiClass>();
getLeastUpperClassesInner(aClass, bClass, supers);
return supers.toArray(new PsiClass[supers.size()]);
}
private static void getLeastUpperClassesInner(PsiClass aClass, PsiClass bClass, Set<PsiClass> supers) {
if (bClass.isInheritor(aClass, true)) {
supers.add(aClass);
}
else {
final PsiClass[] aSupers = aClass.getSupers();
for (int i = 0; i < aSupers.length; i++) {
PsiClass aSuper = aSupers[i];
getLeastUpperClassesInner(aSuper, bClass, supers);
}
}
}
public static boolean isTypeArgumentsApplicable(PsiTypeParameter[] typeParams, PsiSubstitutor substitutor) {
for (int i = 0; i < typeParams.length; i++) {
PsiTypeParameter typeParameter = typeParams[i];
PsiType substituted = substitutor.substitute(typeParameter);
if (substituted == null) return true;
PsiClassType[] extendsTypes = typeParameter.getExtendsListTypes();
for (int j = 0; j < extendsTypes.length; j++) {
PsiType extendsType = substitutor.substitute(extendsTypes[j]);
if (!extendsType.isAssignableFrom(substituted)) {
return false;
}
}
}
return true;
}
public static boolean isFromExternalTypeLanguage (PsiType type) {
return type.getInternalCanonicalText().equals(type.getCanonicalText());
}
public static PsiClass[] getGreatestLowerClasses(final PsiClass aClass, final PsiClass bClass) {
if (InheritanceUtil.isInheritorOrSelf(aClass, bClass, true)) {
return new PsiClass[]{aClass};
}
if (InheritanceUtil.isInheritorOrSelf(bClass, aClass, true)) {
return new PsiClass[]{bClass};
}
final Set<PsiClass> descendants = new LinkedHashSet<PsiClass>();
new Object() {
public void getGreatestLowerClasses(final PsiClass aClass, final PsiClass bClass, final Set<PsiClass> descendants) {
if (aClass.isInheritor(bClass, true)) {
descendants.add(bClass);
}
else {
final PsiSearchHelper helper = aClass.getManager().getSearchHelper();
final PsiClass[] bSubs = helper.findInheritors(bClass, helper.getAccessScope(bClass), true);
for (int i = 0; i < bSubs.length; i++) {
getLeastUpperClassesInner(bSubs[i], aClass, descendants);
}
}
}
}.getGreatestLowerClasses(aClass, bClass, descendants);
return descendants.toArray(new PsiClass[descendants.size()]);
}
}
|
// This source code is available under agreement available at
// You should have received a copy of the agreement
// along with this program; if not, write to Talend SA
// 9 rue Pages 92150 Suresnes, France
package org.talend.dataprep.dataset.adapter.conversions;
import static org.talend.dataprep.conversions.BeanConversionService.fromBean;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;
import org.talend.daikon.exception.TalendRuntimeException;
import org.talend.daikon.exception.error.CommonErrorCodes;
import org.talend.dataprep.api.dataset.DataSetContent;
import org.talend.dataprep.api.dataset.DataSetGovernance;
import org.talend.dataprep.api.dataset.DataSetGovernance.Certification;
import org.talend.dataprep.api.dataset.DataSetLocation;
import org.talend.dataprep.api.dataset.DataSetMetadata;
import org.talend.dataprep.conversions.BeanConversionService;
import org.talend.dataprep.dataset.adapter.Dataset;
import org.talend.dataprep.dataset.adapter.Dataset.CertificationState;
import org.talend.dataprep.dataset.adapter.Datastore;
import org.talend.dataprep.processor.BeanConversionServiceWrapper;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
/**
* Bean Conversion from {@link Dataset} to {@link DataSetMetadata}
*/
@Component
public class DatasetBeanConversion extends BeanConversionServiceWrapper {
private static final Logger LOGGER = LoggerFactory.getLogger(DatasetBeanConversion.class);
private final ObjectMapper objectMapper;
public DatasetBeanConversion(ObjectMapper objectMapper) {
this.objectMapper = objectMapper;
}
@Override
public BeanConversionService doWith(BeanConversionService conversionService, String beanName,
ApplicationContext applicationContext) {
conversionService.register(fromBean(Dataset.class)
.toBeans(DataSetMetadata.class)
.using(DataSetMetadata.class, (dataset, dataSetMetadata) -> {
dataSetMetadata.setName(dataset.getLabel());
dataSetMetadata.setCreationDate(dataset.getCreated());
dataSetMetadata.setLastModificationDate(dataset.getUpdated());
dataSetMetadata.setAuthor(dataset.getOwner());
CertificationState certificationState = dataset.getCertification();
if (certificationState != null) {
DataSetGovernance governance = new DataSetGovernance();
governance.setCertificationStep(Certification.valueOf(certificationState.name()));
dataSetMetadata.setGovernance(governance);
}
JsonNode datasetProperties = dataset.getProperties();
if (datasetProperties == null) {
datasetProperties = objectMapper.createObjectNode();
}
Datastore datastore = dataset.getDatastore();
//FIXME bypass for content / location information about local file or live dataset
if (datastore == null) {
try {
if (datasetProperties.has("content")) {
DataSetContent content =
objectMapper.treeToValue(datasetProperties.get("content"), DataSetContent.class);
dataSetMetadata.setContent(content);
} else {
LOGGER.warn("no dataset content for the dataset [{}]", dataSetMetadata.getId());
}
if (datasetProperties.has("location")) {
DataSetLocation location =
objectMapper.treeToValue(datasetProperties.get("location"), DataSetLocation.class);
dataSetMetadata.setLocation(location);
} else {
LOGGER.warn("no dataset location for the dataset [{}]", dataSetMetadata.getId());
}
} catch (JsonProcessingException e) {
throw new TalendRuntimeException(CommonErrorCodes.UNEXPECTED_EXCEPTION, e);
}
}
// Manage legacy fields that doesn't match data catalog concept
Dataset.DataSetMetadataLegacy dataSetMetadataLegacy = dataset.getDataSetMetadataLegacy();
if (dataSetMetadataLegacy != null) {
dataSetMetadata.setSheetName(dataSetMetadataLegacy.getSheetName());
dataSetMetadata.setSchemaParserResult(dataSetMetadataLegacy.getSchemaParserResult());
dataSetMetadata.setDraft(dataSetMetadataLegacy.isDraft());
dataSetMetadata.setEncoding(dataSetMetadataLegacy.getEncoding());
dataSetMetadata.setTag(dataSetMetadataLegacy.getTag());
}
return dataSetMetadata;
})
.build());
return conversionService;
}
}
|
package org.hisp.dhis.analytics;
import com.google.common.base.MoreObjects;
import org.hisp.dhis.util.DateUtils;
import org.hisp.dhis.calendar.Calendar;
import org.hisp.dhis.calendar.DateTimeUnit;
import org.hisp.dhis.period.PeriodType;
import org.hisp.dhis.scheduling.JobConfiguration;
import java.util.Date;
import java.util.HashSet;
import java.util.Objects;
import java.util.Set;
import static com.google.common.base.Preconditions.checkNotNull;
/**
* Class representing parameters for the analytics table generation process.
*
* @author Lars Helge Overland
*/
public class AnalyticsTableUpdateParams
{
/**
* Number of last years for which to update tables. A zero value indicates
* the "latest" data stored since last full analytics table generation.
*/
private Integer lastYears;
/**
* Indicates whether to skip update of resource tables.
*/
boolean skipResourceTables;
/**
* Analytics table types to skip.
*/
private Set<AnalyticsTableType> skipTableTypes = new HashSet<>();
/**
* Job ID.
*/
private JobConfiguration jobId;
/**
* Start time for update process.
*/
private Date startTime;
/**
* Time of last successful analytics table update.
*/
private Date lastSuccessfulUpdate;
private AnalyticsTableUpdateParams()
{
this.startTime = new Date();
}
// Get methods
public Integer getLastYears()
{
return lastYears;
}
public boolean isSkipResourceTables()
{
return skipResourceTables;
}
public Set<AnalyticsTableType> getSkipTableTypes()
{
return skipTableTypes;
}
public JobConfiguration getJobId()
{
return jobId;
}
public Date getStartTime()
{
return startTime;
}
public Date getLastSuccessfulUpdate()
{
return lastSuccessfulUpdate;
}
/**
* Indicates whether this is a partial update of analytics tables, i.e.
* if only certain partitions are to be updated and not all partitions
* including the main analytics tables.
*/
public boolean isPartialUpdate()
{
return lastYears != null || isLatestUpdate();
}
/**
* Indicates whether this is an update of the "latest" partition.
*/
public boolean isLatestUpdate()
{
return Objects.equals( lastYears, AnalyticsTablePartition.LATEST_PARTITION );
}
// toString
@Override
public String toString()
{
return MoreObjects.toStringHelper( this )
.add( "last years", lastYears )
.add( "skip resource tables", skipResourceTables )
.add( "skip table types", skipTableTypes )
.add( "start time", DateUtils.getLongDateString( startTime ) )
.toString();
}
/**
* Returns the from date based on the last years property, i.e. the first
* day of year relative to the last years property.
*
* @return the from date based on the last years property.
*/
public Date getFromDate()
{
Date earliest = null;
if ( lastYears != null )
{
Calendar calendar = PeriodType.getCalendar();
DateTimeUnit dateTimeUnit = calendar.today();
dateTimeUnit = calendar.minusYears( dateTimeUnit, lastYears - 1 );
dateTimeUnit.setMonth( 1 );
dateTimeUnit.setDay( 1 );
earliest = dateTimeUnit.toJdkDate();
}
return earliest;
}
// Builder of immutable instances
/**
* Returns a new instance of this parameter object.
*/
public AnalyticsTableUpdateParams instance()
{
AnalyticsTableUpdateParams params = new AnalyticsTableUpdateParams();
params.lastYears = this.lastYears;
params.skipResourceTables = this.skipResourceTables;
params.skipTableTypes = new HashSet<>( this.skipTableTypes );
params.jobId = this.jobId;
params.startTime = this.startTime;
params.lastSuccessfulUpdate = this.lastSuccessfulUpdate;
return this;
}
public static Builder newBuilder()
{
return new AnalyticsTableUpdateParams.Builder();
}
public static Builder newBuilder( AnalyticsTableUpdateParams analyticsTableUpdateParams )
{
return new AnalyticsTableUpdateParams.Builder( analyticsTableUpdateParams );
}
/**
* Builder for {@link AnalyticsTableUpdateParams} instances.
*/
public static class Builder
{
private AnalyticsTableUpdateParams params;
protected Builder()
{
this.params = new AnalyticsTableUpdateParams();
}
protected Builder( AnalyticsTableUpdateParams analyticsTableUpdateParams )
{
this.params = analyticsTableUpdateParams.instance();
}
public Builder withLastYears( Integer lastYears )
{
this.params.lastYears = lastYears;
return this;
}
public Builder withLatestPartition()
{
this.params.lastYears = AnalyticsTablePartition.LATEST_PARTITION;
return this;
}
public Builder withSkipResourceTables( boolean skipResourceTables )
{
this.params.skipResourceTables = skipResourceTables;
return this;
}
public Builder withSkipTableTypes( Set<AnalyticsTableType> skipTableTypes )
{
this.params.skipTableTypes = skipTableTypes;
return this;
}
public Builder withJobId( JobConfiguration jobId )
{
this.params.jobId = jobId;
return this;
}
public Builder withLastSuccessfulUpdate( Date lastSuccessfulUpdate )
{
this.params.lastSuccessfulUpdate = lastSuccessfulUpdate;
return this;
}
public Builder withStartTime( Date startTime )
{
this.params.startTime = startTime;
return this;
}
public AnalyticsTableUpdateParams build()
{
checkNotNull( this.params.startTime );
return this.params;
}
}
}
|
package de.charite.compbio.exomiser.cli.options;
import de.charite.compbio.exomiser.core.analysis.Settings.SettingsBuilder;
import org.apache.commons.cli.OptionBuilder;
/**
*
* @author Jules Jacobsen <jules.jacobsen@sanger.ac.uk>
*/
public class PathogenicityFilterCutOffOptionMarshaller extends AbstractOptionMarshaller {
public static final String KEEP_NON_PATHOGENIC_VARIANTS_OPTION = "keep-non-pathogenic";
public PathogenicityFilterCutOffOptionMarshaller() {
option = OptionBuilder
.hasOptionalArg()
.withType(Boolean.class)
.withArgName("true/false")
.withDescription("Keep the predicted non-pathogenic variants that are normally removed by default. "
+ "These are defined as syonymous, intergenic, intronic, upstream, downstream or intronic ncRNA variants. "
+ "This setting can optionally take a true/false argument. Not including the argument is equivalent to specifying 'false'.")
.withLongOpt(KEEP_NON_PATHOGENIC_VARIANTS_OPTION)
.create("P");
}
@Override
public void applyValuesToSettingsBuilder(String[] values, SettingsBuilder settingsBuilder) {
if (values == null) {
//default is to remove the non-pathogenic variants, so this should be false
settingsBuilder.removePathFilterCutOff(true);
} else {
//but the json/properties file specifies true or false, hence the optionArg
settingsBuilder.removePathFilterCutOff(Boolean.parseBoolean(values[0]));
}
}
}
|
package com.github.avarabyeu.jashing.integration.vcs.github.model;
import com.google.gson.annotations.SerializedName;
import java.util.Date;
/**
* Repository model class
*/
public class Repository {
private boolean fork;
private boolean hasDownloads;
private boolean hasIssues;
private boolean hasWiki;
@SerializedName("private")
private boolean isPrivate;
private Date createdAt;
private Date pushedAt;
private Date updatedAt;
private int forks;
private long id;
@SerializedName("open_issues_count")
private int openIssues;
private int size;
private int watchers;
private Repository parent;
private Repository source;
private String cloneUrl;
private String description;
private String homepage;
private String gitUrl;
private String htmlUrl;
private String language;
private String defaultBranch;
private String mirrorUrl;
private String name;
private String sshUrl;
private String svnUrl;
private String url;
private User owner;
/**
* @return fork
*/
public boolean isFork() {
return fork;
}
/**
* @param fork Fork
* @return this repository
*/
public Repository setFork(boolean fork) {
this.fork = fork;
return this;
}
/**
* @return hasDownloads
*/
public boolean isHasDownloads() {
return hasDownloads;
}
/**
* @param hasDownloads Has Downloads
* @return this repository
*/
public Repository setHasDownloads(boolean hasDownloads) {
this.hasDownloads = hasDownloads;
return this;
}
/**
* @return hasIssues
*/
public boolean isHasIssues() {
return hasIssues;
}
/**
* @param hasIssues Has Issues
* @return this repository
*/
public Repository setHasIssues(boolean hasIssues) {
this.hasIssues = hasIssues;
return this;
}
/**
* @return hasWiki
*/
public boolean isHasWiki() {
return hasWiki;
}
/**
* @param hasWiki Has Wiki
* @return this repository
*/
public Repository setHasWiki(boolean hasWiki) {
this.hasWiki = hasWiki;
return this;
}
/**
* @return isPrivate
*/
public boolean isPrivate() {
return isPrivate;
}
/**
* @param isPrivate Is Private
* @return this repository
*/
public Repository setPrivate(boolean isPrivate) {
this.isPrivate = isPrivate;
return this;
}
/**
* @return createdAt
*/
public Date getCreatedAt() {
return createdAt;
}
/**
* @param createdAt Created At
* @return this rdateepository
*/
public Repository setCreatedAt(Date createdAt) {
this.createdAt = createdAt;
return this;
}
/**
* @return pushedAt
*/
public Date getPushedAt() {
return pushedAt;
}
/**
* @param pushedAt Pushed At
* @return this repository
*/
public Repository setPushedAt(Date pushedAt) {
this.pushedAt = pushedAt;
return this;
}
/**
* @return forks
*/
public int getForks() {
return forks;
}
/**
* @param forks Forks
* @return this repository
*/
public Repository setForks(int forks) {
this.forks = forks;
return this;
}
/**
* @return openIssues
*/
public int getOpenIssues() {
return openIssues;
}
/**
* @param openIssues Open Issues
* @return this repository
*/
public Repository setOpenIssues(int openIssues) {
this.openIssues = openIssues;
return this;
}
/**
* @return size
*/
public int getSize() {
return size;
}
/**
* @param size Size
* @return this repository
*/
public Repository setSize(int size) {
this.size = size;
return this;
}
/**
* @return watchers
*/
public int getWatchers() {
return watchers;
}
/**
* @param watchers Watchers
* @return this repository
*/
public Repository setWatchers(int watchers) {
this.watchers = watchers;
return this;
}
/**
* @return parent
*/
public Repository getParent() {
return parent;
}
/**
* @param parent Parent
* @return this repository
*/
public Repository setParent(Repository parent) {
this.parent = parent;
return this;
}
/**
* @return source
*/
public Repository getSource() {
return source;
}
/**
* @param source Source
* @return this repository
*/
public Repository setSource(Repository source) {
this.source = source;
return this;
}
/**
* @return cloneUrl
*/
public String getCloneUrl() {
return cloneUrl;
}
/**
* @param cloneUrl Clone URL
* @return this repository
*/
public Repository setCloneUrl(String cloneUrl) {
this.cloneUrl = cloneUrl;
return this;
}
/**
* @return description
*/
public String getDescription() {
return description;
}
/**
* @param description Description
* @return this repository
*/
public Repository setDescription(String description) {
this.description = description;
return this;
}
/**
* @return homepage
*/
public String getHomepage() {
return homepage;
}
/**
* @param homepage Homepage
* @return this repository
*/
public Repository setHomepage(String homepage) {
this.homepage = homepage;
return this;
}
/**
* @return gitUrl
*/
public String getGitUrl() {
return gitUrl;
}
/**
* @param gitUrl Get URL
* @return this repository
*/
public Repository setGitUrl(String gitUrl) {
this.gitUrl = gitUrl;
return this;
}
/**
* @return htmlUrl
*/
public String getHtmlUrl() {
return htmlUrl;
}
/**
* @param htmlUrl HTML URL
* @return this repository
*/
public Repository setHtmlUrl(String htmlUrl) {
this.htmlUrl = htmlUrl;
return this;
}
/**
* @return language
*/
public String getLanguage() {
return language;
}
/**
* @param language Language
* @return this repository
*/
public Repository setLanguage(String language) {
this.language = language;
return this;
}
/**
* @return defaultBranch
*/
public String getDefaultBranch() {
return defaultBranch;
}
/**
* @param defaultBranch Default Branch
* @return this repository
*/
public Repository setDefaultBranch(String defaultBranch) {
this.defaultBranch = defaultBranch;
return this;
}
/**
* @return masterBranch
*/
@Deprecated
public String getMasterBranch() {
return defaultBranch;
}
/**
* @param masterBranch Master Branch
* @return this repository
*/
@Deprecated
public Repository setMasterBranch(String masterBranch) {
this.defaultBranch = masterBranch;
return this;
}
/**
* @return mirrorUrl
*/
public String getMirrorUrl() {
return mirrorUrl;
}
/**
* @param mirrorUrl Mirror URL
* @return this repository
*/
public Repository setMirrorUrl(String mirrorUrl) {
this.mirrorUrl = mirrorUrl;
return this;
}
/**
* @return name
*/
public String getName() {
return name;
}
/**
* @param name Name
* @return this repository
*/
public Repository setName(String name) {
this.name = name;
return this;
}
/**
* @return sshUrl
*/
public String getSshUrl() {
return sshUrl;
}
/**
* @param sshUrl SSH URL
* @return this repository
*/
public Repository setSshUrl(String sshUrl) {
this.sshUrl = sshUrl;
return this;
}
/**
* @return svnUrl
*/
public String getSvnUrl() {
return svnUrl;
}
/**
* @param svnUrl SVN URL
* @return this repository
*/
public Repository setSvnUrl(String svnUrl) {
this.svnUrl = svnUrl;
return this;
}
/**
* @return url
*/
public String getUrl() {
return url;
}
/**
* @param url URL
* @return this repository
*/
public Repository setUrl(String url) {
this.url = url;
return this;
}
/**
* @return owner
*/
public User getOwner() {
return owner;
}
/**
* @param owner Owner
* @return this repository
*/
public Repository setOwner(User owner) {
this.owner = owner;
return this;
}
/**
* @return updatedAt
*/
public Date getUpdatedAt() {
return updatedAt;
}
/**
* @param updatedAt Updated At
* @return this repository
*/
public Repository setUpdatedAt(Date updatedAt) {
this.updatedAt = updatedAt;
return this;
}
/**
* @return id
*/
public long getId() {
return id;
}
/**
* @param id ID
* @return this repository
*/
public Repository setId(long id) {
this.id = id;
return this;
}
/**
* Generate id for this repository
* @return New generated ID
*/
public String generateId() {
final User owner = this.owner;
final String name = this.name;
if (owner == null || name == null || name.length() == 0)
return null;
final String login = owner.getLogin();
if (login == null || login.length() == 0)
return null;
return login + "/" + name; //$NON-NLS-1$
}
@Override
public String toString() {
return "Repository{" +
"fork=" + fork +
", hasDownloads=" + hasDownloads +
", hasIssues=" + hasIssues +
", hasWiki=" + hasWiki +
", isPrivate=" + isPrivate +
", createdAt=" + createdAt +
", pushedAt=" + pushedAt +
", updatedAt=" + updatedAt +
", forks=" + forks +
", id=" + id +
", openIssues=" + openIssues +
", size=" + size +
", watchers=" + watchers +
", parent=" + parent +
", source=" + source +
", cloneUrl='" + cloneUrl + '\'' +
", description='" + description + '\'' +
", homepage='" + homepage + '\'' +
", gitUrl='" + gitUrl + '\'' +
", htmlUrl='" + htmlUrl + '\'' +
", language='" + language + '\'' +
", defaultBranch='" + defaultBranch + '\'' +
", mirrorUrl='" + mirrorUrl + '\'' +
", name='" + name + '\'' +
", sshUrl='" + sshUrl + '\'' +
", svnUrl='" + svnUrl + '\'' +
", url='" + url + '\'' +
", owner=" + owner +
'}';
}
}
|
/*
* generated by Xtext
*/
package com.rockwellcollins.atc.agree.formatting;
import org.eclipse.xtext.Keyword;
import org.eclipse.xtext.formatting.impl.AbstractDeclarativeFormatter;
import org.eclipse.xtext.formatting.impl.FormattingConfig;
import org.eclipse.xtext.util.Pair;
import com.google.inject.Inject;
import com.rockwellcollins.atc.agree.services.AgreeGrammarAccess;
public class AgreeFormatter extends AbstractDeclarativeFormatter {
@Inject
private AgreeGrammarAccess grammarAccess;
@Override
protected void configureFormatting(FormattingConfig c) {
// It's usually a good idea to activate the following three statements.
// They will add and preserve newlines around comments
c.setLinewrap(0, 1, 2).before(grammarAccess.getSL_COMMENTRule());
// c.setLinewrap(0, 1, 2).before(grammarAccess.getML_COMMENTRule());
// c.setLinewrap(0, 1, 1).after(grammarAccess.getML_COMMENTRule());
c.setAutoLinewrap(120);
// set line wrap after semicolon
for (Keyword keywd : grammarAccess.findKeywords(";")) {
c.setLinewrap().after(keywd);
}
// set no space before dots, commas and semicolons, right paren
for (Keyword keywd : grammarAccess.findKeywords(".", ",", ";", ")")) {
c.setNoSpace().before(keywd);
}
// set no space after dots and right paren
for (Keyword keywd : grammarAccess.findKeywords(".", "(")) {
c.setNoSpace().after(keywd);
}
// set and blank line between specification statements
// But, it seems to not work for positioning with respect to
// abstract base classes such as SpecStatement
c.setLinewrap(2).after(grammarAccess.getSpecStatementRule());
c.setLinewrap(2).before(grammarAccess.getSynchStatementRule());
c.setLinewrap(2).before(grammarAccess.getOrderStatementRule());
c.setLinewrap(2).before(grammarAccess.getPropertyStatementRule());
c.setLinewrap(2).before(grammarAccess.getConstStatementRule());
c.setLinewrap(2).before(grammarAccess.getEnumStatementRule());
c.setLinewrap(2).before(grammarAccess.getEqStatementRule());
c.setLinewrap(2).before(grammarAccess.getAssignStatementRule());
c.setLinewrap(2).before(grammarAccess.getLinearizationDefExprRule());
c.setLinewrap(2).before(grammarAccess.getFnDefExprRule());
c.setLinewrap(2).before(grammarAccess.getLibraryFnDefExprRule());
c.setLinewrap(2).before(grammarAccess.getNodeDefExprRule());
c.setLinewrap(2).before(grammarAccess.getRecordDefExprRule());
c.setLinewrap(2).before(grammarAccess.getInputStatementRule());
// set line wrap before node def, let, tel, each local var
c.setLinewrap().after(grammarAccess.getNodeStmtRule());
c.setLinewrap().after(grammarAccess.getNodeDefExprAccess().getArgsAssignment_3_1_1());
c.setLinewrap().after(grammarAccess.getNodeDefExprAccess().getReturnsKeyword_5());
c.setLinewrap().after(grammarAccess.getNodeBodyExprAccess().getLetKeyword_1());
c.setLinewrap().after(grammarAccess.getNodeBodyExprAccess().getTelKeyword_3());
c.setIndentationIncrement().after(grammarAccess.getNodeBodyExprAccess().getLetKeyword_1());
c.setIndentationDecrement().before(grammarAccess.getNodeBodyExprAccess().getTelKeyword_3());
// set line indentation inside for ITE
c.setLinewrap().before(grammarAccess.getIfThenElseExprAccess().getThenKeyword_0_3());
//c.setIndentationIncrement().before(grammarAccess.getIfThenElseExprAccess().getBExprParserRuleCall_0_4_0());
//c.setIndentationDecrement().after(grammarAccess.getIfThenElseExprAccess().getBExprParserRuleCall_0_4_0());
c.setLinewrap().before(grammarAccess.getIfThenElseExprAccess().getElseKeyword_0_5());
//c.setIndentationIncrement().before(grammarAccess.getIfThenElseExprAccess().getCExprParserRuleCall_0_6_0());
//c.setIndentationDecrement().after(grammarAccess.getIfThenElseExprAccess().getCExprParserRuleCall_0_6_0());
// set line indentation inside all parentheses
//grammarAccess.getRecordUpdateExprRule().g
for (Pair<Keyword, Keyword> p : grammarAccess.findKeywordPairs("(", ")")) {
c.setIndentationIncrement().after(p.getFirst());
c.setIndentationDecrement().before(p.getSecond());
}
// set line indentation inside all curly brackets
// set line wrap after each left curly bracket
// set line wrap around each right curly bracket
//grammarAccess.getRecordUpdateExprRule().g
for (Pair<Keyword, Keyword> p : grammarAccess.findKeywordPairs("{", "}")) {
c.setIndentationIncrement().after(p.getFirst());
c.setIndentationDecrement().before(p.getSecond());
c.setLinewrap().after(p.getFirst());
c.setLinewrap().around(p.getSecond());
}
}
}
|
package org.spongepowered.forge.applaunch.loading.moddiscovery.locator;
import cpw.mods.modlauncher.api.LamdbaExceptionUtils;
import net.minecraftforge.fml.loading.LogMarkers;
import net.minecraftforge.fml.loading.ModDirTransformerDiscoverer;
import net.minecraftforge.fml.loading.StringUtils;
import net.minecraftforge.fml.loading.moddiscovery.AbstractJarFileLocator;
import net.minecraftforge.forgespi.locating.IModFile;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.spongepowered.common.applaunch.AppLaunch;
import org.spongepowered.forge.applaunch.loading.moddiscovery.ModFileParsers;
import java.nio.file.FileSystem;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
public final class PluginsFolderLocator extends AbstractJarFileLocator {
private static final Logger LOGGER = LogManager.getLogger();
@Override
public List<IModFile> scanMods() {
final List<Path> pluginDirectories = AppLaunch.pluginPlatform().pluginDirectories();
final List<IModFile> modFiles = new ArrayList<>();
for (final Path pluginDirectory : pluginDirectories) {
PluginsFolderLocator.LOGGER.debug(LogMarkers.SCAN, "Scanning plugins directory '{}' for plugins", pluginDirectory);
modFiles.addAll(this.scanForModsIn(pluginDirectory));
}
return modFiles;
}
private List<IModFile> scanForModsIn(final Path pluginsDirectory) {
final List<Path> excluded = ModDirTransformerDiscoverer.allExcluded();
return LamdbaExceptionUtils.uncheck(() -> Files.list(pluginsDirectory))
.filter((p) -> !excluded.contains(p))
.sorted(Comparator.comparing((path) -> StringUtils.toLowerCase(path.getFileName().toString())))
.filter((p) -> StringUtils.toLowerCase(p.getFileName().toString()).endsWith(".jar"))
.map((p) -> ModFileParsers.newPluginInstance(p, this, "plugins"))
.peek((f) -> this.modJars.compute(f, (mf, fs) -> this.createFileSystem(mf)))
.filter(f -> {
if (!f.identifyMods()) {
final FileSystem fs = this.modJars.remove(f);
if (fs != null) {
LamdbaExceptionUtils.uncheck(fs::close);
}
return false;
}
return true;
})
.collect(Collectors.toList());
}
@Override
public String name() {
return "plugins directory";
}
@Override
public void initArguments(final Map<String, ?> arguments) {
}
}
|
package org.eclipse.persistence.platform.server.wls;
import java.lang.reflect.Method;
import java.security.AccessController;
import javax.management.MBeanServer;
import javax.management.ObjectName;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import org.eclipse.persistence.internal.security.PrivilegedAccessHelper;
import org.eclipse.persistence.internal.security.PrivilegedMethodInvoker;
import org.eclipse.persistence.logging.SessionLog;
import org.eclipse.persistence.platform.server.JMXEnabledPlatform;
import org.eclipse.persistence.services.weblogic.MBeanWebLogicRuntimeServices;
import org.eclipse.persistence.sessions.DatabaseSession;
/**
* PUBLIC:
*
* This is the concrete subclass responsible for representing WebLogic 10 specific behavior.
* This includes WebLogic 10.3 behavior.
*/
public class WebLogic_10_Platform extends WebLogic_9_Platform implements JMXEnabledPlatform {
// see http://docs.oracle.com/middleware/1213/wls/JMXCU/understandwls.htm#i1127767
/** This JNDI address is for JMX MBean registration */
private static final String JMX_JNDI_RUNTIME_REGISTER = "java:comp/env/jmx/runtime";
/** This JNDI address is for JMX MBean unregistration */
private static final String JMX_JNDI_RUNTIME_UNREGISTER = "java:comp/jmx/runtime";
/** This persistence.xml or sessions.xml property is used to override the moduleName */
protected static final String SERVER_SPECIFIC_MODULENAME_PROPERTY = "eclipselink.weblogic.moduleName";
/** This persistence.xml or sessions.xml property is used to override the applicationName */
protected static final String SERVER_SPECIFIC_APPLICATIONNAME_PROPERTY = "eclipselink.weblogic.applicationName";
/**
* The following constants and attributes are used during reflective API calls
*/
/** Cache the WebLogic ThreadPoolRuntime for performance */
private ObjectName wlsThreadPoolRuntime = null;
private static final String WLS_SERVICE_KEY = "com.bea:Name=RuntimeService,Type=weblogic.management.mbeanservers.runtime.RuntimeServiceMBean";
private static final String WLS_SERVER_RUNTIME = "ServerRuntime";
private static final String WLS_THREADPOOL_RUNTIME = "ThreadPoolRuntime";
private static final String WLS_EXECUTE_THREAD_GET_METHOD_NAME = "getExecuteThread";
private static final String WLS_APPLICATION_NAME_GET_METHOD_NAME = "getApplicationName";
private static final String WLS_MODULE_NAME_GET_METHOD_NAME = "getModuleName";
/** Search String in WebLogic ClassLoader for the application:persistence_unit name */
private static final String WLS_CLASSLOADER_APPLICATION_PU_SEARCH_STRING_PREFIX = "annotation: ";
static {
/** Override by subclass: Search String in application server ClassLoader for the application:persistence_unit name */
APP_SERVER_CLASSLOADER_APPLICATION_PU_SEARCH_STRING_PREFIX = "/deploy/";
/** Override by subclass: Search String in application server session for ejb modules */
APP_SERVER_CLASSLOADER_MODULE_EJB_SEARCH_STRING_PREFIX = ".jar/";
/** Override by subclass: Search String in application server session for war modules */
APP_SERVER_CLASSLOADER_MODULE_WAR_SEARCH_STRING_PREFIX = ".war/";
APP_SERVER_CLASSLOADER_APPLICATION_PU_SEARCH_STRING_POSTFIX = "postfix,match~not;required^";
APP_SERVER_CLASSLOADER_MODULE_EJB_WAR_SEARCH_STRING_POSTFIX = "postfix,match~not;required^";
}
/**
* INTERNAL:
* Default Constructor: All behavior for the default constructor is inherited
*/
public WebLogic_10_Platform(DatabaseSession newDatabaseSession) {
super(newDatabaseSession);
this.enableRuntimeServices();
// Create the JMX MBean specific to this platform for later registration
this.prepareServerSpecificServicesMBean();
}
@Override
public boolean isRuntimeServicesEnabledDefault() {
return true;
}
/**
* INTERNAL:
* prepareServerSpecificServicesMBean(): Server specific implementation of the
* creation and deployment of the JMX MBean to provide runtime services for the
* databaseSession.
*
* Default is to do nothing.
* Implementing platform classes must override this function and supply
* the server specific MBean instance for later registration by calling it in the constructor.
*
* @return void
* @see #isRuntimeServicesEnabled()
* @see #disableRuntimeServices()
* @see #registerMBean()
*/
public void prepareServerSpecificServicesMBean() {
// No check for an existing cached MBean - we will replace it if it exists
if(shouldRegisterRuntimeBean) {
this.setRuntimeServicesMBean(new MBeanWebLogicRuntimeServices(getDatabaseSession()));
}
}
/**
* INTERNAL:
* serverSpecificRegisterMBean(): Server specific implementation of the
* creation and deployment of the JMX MBean to provide runtime services for my
* databaseSession.
*
* @return void
* @see #isRuntimeServicesEnabled()
* @see #disableRuntimeServices()
* @see #registerMBean()
*/
@Override
public void serverSpecificRegisterMBean() {
super.serverSpecificRegisterMBean();
// get and cache module and application name during registration
initializeApplicationNameAndModuleName();
}
/**
* INTERNAL:
* Return the MBeanServer to be used for MBean registration and deregistration.<br>
* This MBeanServer reference is lazy loaded and cached on the platform.<br>
* There are multiple ways of getting the MBeanServer<br>
* <p>
* 1) MBeanServerFactory static function - working for 3 of 4 servers WebSphere, JBoss and Glassfish in a generic way<br>
* - JBoss returns 2 MBeanServers in the List - but one of them has a null domain - we don't use that one<br>
* - WebLogic may return 2 MBeanServers - in that case we want to register with the one containing the "com.bea" tree
* 2) ManagementFactory static function - what is the difference in using this one over the one returning a List of servers<br>
* 3) JNDI lookup<br>
* 4) Direct server specific native API<br></p>
* We are using method (3)<br>
*
* @return the JMX specification MBeanServer
*/
@Override
public MBeanServer getMBeanServer() {
//super.getMBeanServer(); keep commented except for generic registration testing
// 328006: This function overrides the generic version used for WebSphere, JBoss and Glassfish
// Get a possible cached MBeanServer from the superclass first
if(null == mBeanServer) {
Context initialContext = null;
try {
initialContext = new InitialContext();
try {
mBeanServer = (MBeanServer) initialContext.lookup(JMX_JNDI_RUNTIME_REGISTER);
if (null == mBeanServer) {
getAbstractSession().log(SessionLog.WARNING, SessionLog.SERVER,
"failed_to_find_mbean_server", "null returned from JNDI lookup of " + JMX_JNDI_RUNTIME_REGISTER);
}
} catch (NamingException ne1) {
//#440018 Fallback for the case when the JMX client classes are not located in a Java EE module
mBeanServer = (MBeanServer) initialContext.lookup(JMX_JNDI_RUNTIME_UNREGISTER);
if (null == mBeanServer) {
getAbstractSession().log(SessionLog.WARNING, SessionLog.SERVER,
"failed_to_find_mbean_server", "null returned from JNDI lookup of " + JMX_JNDI_RUNTIME_UNREGISTER);
}
}
if (mBeanServer != null) {
// Verify that this is a weblogic.management.jmx.mbeanserver.WLSMBeanServer
if(mBeanServer.toString().indexOf("WLSMBeanServer") < 0) {
// MBeanServer is not a WebLogic type - likely a com.sun.jmx.mbeanserver.JmxMBeanServer
getAbstractSession().log(SessionLog.FINEST, SessionLog.SERVER, "sequencing_connected", null);
}
getAbstractSession().log(SessionLog.FINER, SessionLog.SERVER,
"jmx_mbean_runtime_services_registration_mbeanserver_print",
new Object[]{mBeanServer, mBeanServer.getMBeanCount(), mBeanServer.getDefaultDomain(), 0});
}
} catch (NamingException ne) {
getAbstractSession().log(SessionLog.WARNING, SessionLog.SERVER, "failed_to_find_mbean_server", ne);
} catch (Exception exception) {
getAbstractSession().log(SessionLog.WARNING, SessionLog.SERVER, "problem_registering_mbean", exception);
} finally {
// close the context
// see http://e-docs.bea.com/wls/docs81/jndi/jndi.html#471919
// see http://e-docs.bea.com/wls/docs100/jndi/jndi.html#wp467275
try {
if(null != initialContext) {
initialContext.close();
}
} catch (NamingException ne) {
// exceptions on context close will be ignored, the context will be GC'd
}
}
}
return mBeanServer;
}
/**
* INTERNAL:
* Get the applicationName and moduleName from the runtime WebLogic MBean reflectively
* @return
* @deprecated
*/
protected void initializeApplicationNameAndModuleName() {
// use non-reflective superclass method that searches the database session and classLoader strings
// to be DEPRECATED
// Get property from persistence.xml or sessions.xml
String jpaModuleName = (String)getDatabaseSession().getProperty(SERVER_SPECIFIC_MODULENAME_PROPERTY);
String jpaApplicationName = (String)getDatabaseSession().getProperty(SERVER_SPECIFIC_APPLICATIONNAME_PROPERTY);
if (jpaModuleName != null) {
setModuleName(jpaModuleName);
} else {
jpaModuleName = getModuleOrApplicationName(WLS_MODULE_NAME_GET_METHOD_NAME);
// If we are running a version of WebLogic 10.3 that does not support ExecuteThreadRuntime (from 10.3+) then use the ClassLoader
if(null != jpaModuleName && jpaModuleName.indexOf("@") != -1) {
setModuleName(jpaModuleName.substring(jpaModuleName.indexOf("@") + 1));
} else {
setModuleName(jpaModuleName);
}
}
if (jpaApplicationName != null) {
setApplicationName(jpaApplicationName);
} else {
jpaApplicationName = getModuleOrApplicationName(WLS_APPLICATION_NAME_GET_METHOD_NAME);
// defer to the superclass implementation
if(null == jpaApplicationName) {
jpaApplicationName = super.getApplicationName();
}
// If we are running a version of WebLogic 10.3 that does not support ExecuteThreadRuntime (from 10.3+) then use the ClassLoader
if(null != jpaApplicationName && jpaApplicationName.indexOf("@") > -1) {
setApplicationName(jpaApplicationName.substring(jpaApplicationName.indexOf("@") + 1));
} else {
setApplicationName(jpaApplicationName);
}
}
// TODO: remove: Final check for null values
if(null == getApplicationName()) {
setApplicationName(DEFAULT_SERVER_NAME_AND_VERSION);
}
if(null == getModuleName()) {
setModuleName(DEFAULT_SERVER_NAME_AND_VERSION);
}
getAbstractSession().log(SessionLog.FINEST, SessionLog.SERVER, "mbean_get_application_name",
getDatabaseSession().getName(), getApplicationName());
getAbstractSession().log(SessionLog.FINEST, SessionLog.SERVER, "mbean_get_module_name",
getDatabaseSession().getName(), getModuleName());
}
/**
* INTERNAL:
* This method will return the application|module name for WebLogic.
* If the call to executeThread on the MBean fails - return the current classloader
* Thread.currentThread().getContextClassLoader()
*
* ER 248746: Use reflection to obtain the application name (EJB, Web or MDB module)
* Get either a String containing the module/applicationName or a WebLogic classLoader that contains the module/applicationName in the format...
* weblogic.utils.classloaders.ChangeAwareClassLoader@19bb43f finder: weblogic.utils.classloaders.CodeGenClassFinder@ab7c2e annotation: org.eclipse.persistence.example.jpa.server.weblogic.enterpriseEAR@enterprise
* If the getExecuteThread call failed, use the classloader string representation as backup.
* If the classloader is not in the correct format, defer to superclass.
*
* @return String module|application Name from WLS
*/
private String getModuleOrApplicationName(String getMethodName) {
Object classLoaderOrString = null;//this.getDatabaseSession().getPlatform().getConversionManager().getLoader();
Object executeThread = getExecuteThreadFromMBean();
if (executeThread != null) {
try {
// perform a reflective public java.lang.String
// weblogic.work.ExecuteThreadRuntime.<getMethodName>
Method getMethod = PrivilegedAccessHelper.getPublicMethod(executeThread.getClass(), getMethodName, new Class[] {}, false);
if (PrivilegedAccessHelper.shouldUsePrivilegedAccess()) {
classLoaderOrString = AccessController.doPrivileged(new PrivilegedMethodInvoker(getMethod, executeThread, (Object[]) null));
} else {
classLoaderOrString = PrivilegedAccessHelper.invokeMethod(getMethod, executeThread);
}
if(classLoaderOrString instanceof ClassLoader) {
// If we are running a version of WebLogic 10.3 that does not support ExecuteThreadRuntime (from 10.3+) then use the ClassLoader
String jpaModuleNameRoot = ((ClassLoader)classLoaderOrString).toString();
if(null != jpaModuleNameRoot) {
int startIndex = jpaModuleNameRoot.indexOf(
WLS_CLASSLOADER_APPLICATION_PU_SEARCH_STRING_PREFIX);
if(startIndex > -1) {
classLoaderOrString = jpaModuleNameRoot.substring(startIndex +
WLS_CLASSLOADER_APPLICATION_PU_SEARCH_STRING_PREFIX.length());
}
}
}
} catch (Exception ex) {
/*
* If the reflective call to ExecuteThreadRuntime failed for
* this an older version of WebLogic 10.3 failed, use the
* classloader as a backup method
*/
getAbstractSession().log(SessionLog.WARNING, SessionLog.SERVER, "problem_with_reflective_weblogic_call_mbean", ex, getMethodName);
}
}
return (String)classLoaderOrString;
}
/**
* INTERNAL:
* This convenience method will look up a WebLogic execute thread from the runtime
* MBean tree. The execute thread contains application information. This code
* will use the name of the current thread to lookup the corresponding ExecuteThread.
* The ExecuteThread will allow us to obtain the application name (and version, etc).
*
* Note that the MBeanServer and ThreadPoolRuntime instances will be cached for
* performance.
*
* @return application name or null if the name cannot be obtained
*/
private Object getExecuteThreadFromMBean() {
// Initialize the threadPoolRuntime and get the executeThreadRuntime
//this.getDatabaseSession().getPlatform().getConversionManager().getLoader();
if (getMBeanServer() != null) {
// Lazy load the ThreadPoolRuntime instance
if (wlsThreadPoolRuntime == null) {
try {
ObjectName service = new ObjectName(WLS_SERVICE_KEY);
ObjectName serverRuntime = (ObjectName) getMBeanServer().getAttribute(service, WLS_SERVER_RUNTIME);
wlsThreadPoolRuntime = (ObjectName) getMBeanServer().getAttribute(serverRuntime, WLS_THREADPOOL_RUNTIME);
} catch (Exception ex) {
getAbstractSession().log(SessionLog.WARNING, SessionLog.SERVER, "jmx_mbean_runtime_services_threadpool_initialize_failed", ex);
}
}
// Get the executeThreadRuntimeObject
if (wlsThreadPoolRuntime != null) {
try {
// Perform a reflective getExecuteThread()
return getMBeanServer().invoke(wlsThreadPoolRuntime,
WLS_EXECUTE_THREAD_GET_METHOD_NAME,
new Object[] { Thread.currentThread().getName() }, new String[] { String.class.getName() });
} catch (Exception ex) {
/*
* If the reflective call to get the executeThreadRuntime object failed on the MBean because
* this an older version of WebLogic 10.3, continue and use the classloader as a backup method
*/
getAbstractSession().log(SessionLog.WARNING, SessionLog.SERVER,
"jmx_mbean_runtime_services_get_executethreadruntime_object_failed", ex);
}
}
}
return null;
}
/**
* Return the method for the WebLogic JDBC connection wrapper vendorConnection.
* WLS 10.3.4.0 added a getVendorConnectionSafe that does not invalidate the connection,
* so use this if available.
*/
protected Method getVendorConnectionMethod() {
if ((this.vendorConnectionMethod == null) && (!getWebLogicConnectionClass().equals(void.class))) {
try {
this.vendorConnectionMethod = PrivilegedAccessHelper.getDeclaredMethod(getWebLogicConnectionClass(), "getVendorConnectionSafe", new Class[0]);
} catch (NoSuchMethodException not1034) {
try {
this.vendorConnectionMethod = PrivilegedAccessHelper.getDeclaredMethod(getWebLogicConnectionClass(), "getVendorConnection", new Class[0]);
} catch (NoSuchMethodException exception) {
getDatabaseSession().getSessionLog().logThrowable(SessionLog.WARNING, SessionLog.SERVER, exception);
}
}
}
return this.vendorConnectionMethod;
}
}
|
package org.jtalks.jcommune.web.controller;
import org.jtalks.jcommune.model.entity.JCUser;
import org.jtalks.jcommune.model.entity.Language;
import org.jtalks.jcommune.model.entity.Post;
import org.jtalks.jcommune.service.PostService;
import org.jtalks.jcommune.service.UserService;
import org.jtalks.jcommune.service.exceptions.NotFoundException;
import org.jtalks.jcommune.service.nontransactional.ImageConverter;
import org.jtalks.jcommune.web.dto.EditUserProfileDto;
import org.jtalks.jcommune.web.dto.json.JsonResponse;
import org.jtalks.jcommune.web.dto.json.JsonResponseStatus;
import org.jtalks.jcommune.web.util.BreadcrumbBuilder;
import org.jtalks.jcommune.web.validation.editors.DefaultStringEditor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.propertyeditors.StringTrimmerEditor;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.LocaleResolver;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.i18n.CookieLocaleResolver;
import org.springframework.web.servlet.support.RequestContextUtils;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.util.Locale;
/**
* Controller for User related actions: registration, user profile operations and so on.
*
* @author Kirill Afonin
* @author Alexandre Teterin
* @author Max Malakhov
* @author Eugeny Batov
* @author Evgeniy Naumenko
* @author Anuar_Nurmakanov
*/
@Controller
public class UserProfileController {
public static final String EDIT_PROFILE = "editProfile";
public static final String EDITED_USER = "editedUser";
public static final String BREADCRUMB_LIST = "breadcrumbList";
private UserService userService;
private BreadcrumbBuilder breadcrumbBuilder;
private ImageConverter imageConverter;
private PostService postService;
/**
* This method turns the trim binder on. Trim binder
* removes leading and trailing spaces from the submitted fields.
* So, it ensures, that all validations will be applied to
* trimmed field values only.
* <p/> There is no need for trim edit password fields,
* so they are processed with {@link DefaultStringEditor}
* @param binder Binder object to be injected
*/
@InitBinder
public void initBinder(WebDataBinder binder) {
binder.registerCustomEditor(String.class, "newUserPassword", new DefaultStringEditor(true));
binder.registerCustomEditor(String.class, "newUserPasswordConfirm", new DefaultStringEditor(true));
binder.registerCustomEditor(String.class, new StringTrimmerEditor(true));
}
/**
* @param userService to get current user and user by id
* @param breadcrumbBuilder the object which provides actions on {@link BreadcrumbBuilder} entity
* @param imageConverter to prepare user avatar for view
* @param postService to get all user's posts
*/
@Autowired
public UserProfileController(UserService userService,
BreadcrumbBuilder breadcrumbBuilder,
@Qualifier("avatarPreprocessor")
ImageConverter imageConverter,
PostService postService) {
this.userService = userService;
this.breadcrumbBuilder = breadcrumbBuilder;
this.imageConverter = imageConverter;
this.postService = postService;
}
/**
* Show user profile page with user info.
*
* @param id user identifier
* @return user details view with {@link JCUser} object.
* @throws NotFoundException if user with given id not found.
*/
@RequestMapping(value = "/users/{id}", method = RequestMethod.GET)
public ModelAndView showProfilePage(@PathVariable Long id) throws NotFoundException {
JCUser user = userService.get(id);
return getUserProfileModelAndView(user);
}
/**
* This method is a shortcut for user profile access. It may be usefull when we haven't got
* the specific id, but simply want to access current user's profile.
* <p/>
* Requires user to be authorized.
*
* @return user details view with {@link JCUser} object.
*/
@RequestMapping(value = "/user", method = RequestMethod.GET)
public ModelAndView showCurrentUserProfilePage() {
JCUser user = userService.getCurrentUser();
return getUserProfileModelAndView(user);
}
/**
* Formats model and view for representing user's details
*
* @param user user
* @return user's details
*/
private ModelAndView getUserProfileModelAndView(JCUser user){
return new ModelAndView("userDetails")
.addObject("user", user)
// bind separately to get localized value
.addObject("language", user.getLanguage());
}
/**
* Show edit user profile page for current logged in user.
*
* @return edit user profile page
* @throws NotFoundException throws if current logged in user was not found
*/
@RequestMapping(value = "/users/edit/{editedUserId}", method = RequestMethod.GET)
public ModelAndView startEditUserProfile(@PathVariable Long editedUserId) throws NotFoundException {
checkPermissionsToEditProfile(editedUserId);
JCUser editedUser = userService.get(editedUserId);
EditUserProfileDto editedUserDto = convertUserForView(editedUser);
ModelAndView mav = new ModelAndView(EDIT_PROFILE, EDITED_USER, editedUserDto);
mav.addObject("contacts", editedUser.getUserContacts());
return mav;
}
/**
* Converts passed user to data transfer object for view.
*
* @param user passed user
* @return data transfer object for view
*/
private EditUserProfileDto convertUserForView(JCUser user) {
EditUserProfileDto editUserProfileDto = new EditUserProfileDto(user);
byte[] avatar = user.getAvatar();
editUserProfileDto.setAvatar(imageConverter.prepareHtmlImgSrc(avatar));
return editUserProfileDto;
}
/**
* Update user profile info. Check if the user enter valid data and update profile in database.
* In error case return into the edit profile page and draw the error.
* <p/>
*
* @param editedProfileDto dto populated by user
* @param result binding result which contains the validation result
* @param response http servlet response
* @return in case of errors return back to edit profile page, in another case return to user details page
* @throws NotFoundException if edited user doesn't exist in system
*/
private void checkPermissionsToEditProfile(long editedUserId) {
JCUser editorUser = userService.getCurrentUser();
if (editorUser.getId() == editedUserId) {
userService.checkPermissionToEditOwnProfile(editorUser.getId());
} else {
userService.checkPermissionToEditOtherProfiles(editorUser.getId());
}
}
/**
* Show page with post of user.
* SpEL pattern in a var name indicates we want to consume all the symbols in a var,
* even dots, which Spring MVC uses as file extension delimiters by default.
*
* @param page number current page
* @param id database user identifier
* @return post list of user
* @throws NotFoundException if user with given id not found.
*/
@RequestMapping(value = "/users/{id}/postList", method = RequestMethod.GET)
public ModelAndView showUserPostList(@PathVariable Long id,
@RequestParam(value = "page", defaultValue = "1",
required = false) String page) throws NotFoundException {
JCUser user = userService.get(id);
Page<Post> postsPage = postService.getPostsOfUser(user, page);
return new ModelAndView("userPostList")
.addObject("user", user)
.addObject("postsPage", postsPage)
.addObject(BREADCRUMB_LIST, breadcrumbBuilder.getForumBreadcrumb());
}
@RequestMapping(value = "**/language", method = RequestMethod.GET)
public JsonResponse saveUserLanguage(/*@PathVariable("lang") String lang,*/ @RequestParam(value = "lang") String lang, HttpServletResponse response, HttpServletRequest request) throws ServletException {
JCUser jcuser = userService.getCurrentUser();
if(!jcuser.isAnonymous()){
Language languageFromRequest = Language.byLocale(new Locale(lang));
try{
jcuser.setLanguage(languageFromRequest);
userService.saveEditedUserProfile(jcuser.getId(), new EditUserProfileDto(jcuser).getUserInfoContainer());
}catch (Exception e){
throw new ServletException("Language save failed.");
}
}
LocaleResolver localeResolver = RequestContextUtils.getLocaleResolver(request);
localeResolver.setLocale(request, response, jcuser.getLanguage().getLocale());
// return "redirect:" + request.getHeader("Referer");
return new JsonResponse(JsonResponseStatus.SUCCESS, null);
}
}
|
package com.atlassian.jira.plugins.dvcs.spi.github.webwork;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.atlassian.jira.plugins.dvcs.exception.SourceControlException;
import com.atlassian.jira.plugins.dvcs.exception.SourceControlException.InvalidResponseException;
import com.atlassian.jira.plugins.dvcs.util.CustomStringUtils;
public class GithubOAuthUtils
{
private final Logger log = LoggerFactory.getLogger(GithubOAuthUtils.class);
private final String baseUrl;
private final String clientId;
private final String secret;
public GithubOAuthUtils(String baseUrl, String clientId, String secret)
{
this.baseUrl = baseUrl;
this.clientId = clientId;
this.secret = secret;
}
public String createGithubRedirectUrl(String nextAction, String url, String xsrfToken,
String organization, String autoLinking, String autoSmartCommits)
{
String encodedRepositoryUrl = encode(url);
// Redirect back URL
String redirectBackUrl = baseUrl + "/secure/admin/" + nextAction
+ ".jspa?url=" + encodedRepositoryUrl + "&atl_token=" + xsrfToken + "&organization="
+ organization + "&autoLinking=" + autoLinking + "&autoSmartCommits=" + autoSmartCommits;
String encodedRedirectBackUrl = encode(redirectBackUrl);
// build URL to github
String githubAuthorizeUrl = url + "/login/oauth/authorize?scope=repo&client_id="
+ clientId + "&redirect_uri=" + encodedRedirectBackUrl;
return githubAuthorizeUrl;
}
public String requestAccessToken(String githubHostUrl, String code)
{
log.debug("Requesting access token at " + githubHostUrl + " with code " + code);
URL url;
HttpURLConnection conn;
BufferedReader rd;
String line;
String result = "";
if (StringUtils.isEmpty(code))
{
throw new SourceControlException("Ops, no access code returned. Did you click Allow?");
}
String githubUrl = githubUrl(githubHostUrl);
try
{
String requestUrl = githubUrl + "/login/oauth/access_token";
String urlParameters = "client_id=" + clientId + "&client_secret=" + secret + "&code=" + code;
log.debug("requestAccessToken() - " + requestUrl + " with parameters " + urlParameters);
url = new URL(requestUrl);
conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setInstanceFollowRedirects(true);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
conn.setRequestProperty("charset", "utf-8");
conn.setRequestProperty("Content-Length", "" + Integer.toString(urlParameters.getBytes().length));
conn.setUseCaches (false);
DataOutputStream wr = new DataOutputStream(conn.getOutputStream ());
wr.writeBytes(urlParameters);
wr.flush();
wr.close();
rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
while ((line = rd.readLine()) != null)
{
log.debug("RESPONSE: " + line);
result += line;
}
rd.close();
} catch (MalformedURLException e)
{
throw new SourceControlException("Error obtaining access token.",e);
} catch (IOException ioe)
{
throw new SourceControlException("Error obtaining access token. Cannot access " + githubUrl + " from Jira.",ioe);
}
catch (Exception e)
{
throw new SourceControlException("Error obtaining access token. Please check your credentials.",e);
}
if (result.startsWith("error="))
{
String errorCode = result.replaceAll("error=", "");
String error = errorCode;
if (errorCode.equals("incorrect_client_credentials"))
{
error = "Incorrect client credentials";
} else if (errorCode.equals("bad_verification_code"))
{
error = "Bad verification code";
}
throw new SourceControlException("Error obtaining access token: " + error);
} else if (!result.startsWith("access_token"))
{
log.error("Requested access token response is invalid");
throw new InvalidResponseException("Error obtaining access token. Response is invalid.");
}
return result.replaceAll("access_token=([^&]*).*", "$1");
}
private String githubUrl(String githubHostUrl)
{
return StringUtils.isNotBlank(githubHostUrl) ? githubHostUrl : "https://github.com";
}
public String requestAccessToken(String code)
{
return requestAccessToken(null, code);
}
public static String encode(String url)
{
return CustomStringUtils.encode(url);
}
}
|
package org.languagetool.rules.fr;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import org.languagetool.AnalyzedToken;
import org.languagetool.AnalyzedTokenReadings;
import org.languagetool.language.French;
import org.languagetool.rules.*;
import org.languagetool.rules.patterns.RuleFilter;
import org.languagetool.synthesis.FrenchSynthesizer;
public class PostponedAdjectiveConcordanceFilter extends RuleFilter {
/**
* Patterns
*/
private final int maxLevels = 4;
private static final Pattern NOM = Pattern.compile("[NZ] .*");
private static final Pattern NOM_MS = Pattern.compile("[NZ] m s");
private static final Pattern NOM_FS = Pattern.compile("[NZ] f s");
private static final Pattern NOM_MP = Pattern.compile("[NZ] m p");
private static final Pattern NOM_MN = Pattern.compile("[NZ] m sp");
private static final Pattern NOM_FP = Pattern.compile("[NZ] f p");
private static final Pattern NOM_CS = Pattern.compile("[NZ] e s");
private static final Pattern NOM_CP = Pattern.compile("[NZ] e sp");
private static final Pattern NOM_DET = Pattern.compile("[NZ] .*|(P\\+)?D .*");
private static final Pattern _GN_ = Pattern.compile("_GN_.*");
private static final Pattern _GN_MS = Pattern.compile("_GN_MS");
private static final Pattern _GN_FS = Pattern.compile("_GN_FS");
private static final Pattern _GN_MP = Pattern.compile("_GN_MP");
private static final Pattern _GN_FP = Pattern.compile("_GN_FP");
private static final Pattern _GN_CS = Pattern.compile("_GN_[MF]S");
private static final Pattern _GN_CP = Pattern.compile("_GN_[MF]P");
private static final Pattern _GN_MN = Pattern.compile("_GN_M[SP]");
private static final Pattern _GN_FN = Pattern.compile("_GN_F[SP]");
private static final Pattern DET = Pattern.compile("(P\\+)?D .*");
private static final Pattern DET_CS = Pattern.compile("(P\\+)?D e s");
private static final Pattern DET_MS = Pattern.compile("(P\\+)?D m s");
private static final Pattern DET_FS = Pattern.compile("(P\\+)?D f s");
private static final Pattern DET_MP = Pattern.compile("(P\\+)?D m p");
private static final Pattern DET_FP = Pattern.compile("(P\\+)?D f p");
private static final Pattern DET_CP = Pattern.compile("(P\\+)?D e p"); // NEW for French!!
private static final Pattern GN_MS = Pattern.compile("[NZ] [me] (s|sp)|J [me] (s|sp)|V ppa m s|(P\\+)?D m (s|sp)");
private static final Pattern GN_FS = Pattern.compile("[NZ] [fe] (s|sp)|J [fe] (s|sp)|V ppa f s|(P\\+)?D f (s|sp)");
private static final Pattern GN_MP = Pattern.compile("[NZ] [me] (p|sp)|J [me] (p|sp)|V ppa m p|(P\\+)?D m (p|sp)");
private static final Pattern GN_FP = Pattern.compile("[NZ] [fe] (p|sp)|J [fe] (p|sp)|V ppa f p|(P\\+)?D f (p|sp)");
private static final Pattern GN_CP = Pattern.compile("[NZ] [fme] (p|sp)|J [fme] (p|sp)|(P\\+)?D [fme] (p|sp)");
private static final Pattern GN_CS = Pattern.compile("[NZ] [fme] (s|sp)|J [fme] (s|sp)|(P\\+)?D [fme] (s|sp)");
private static final Pattern GN_MN = Pattern.compile("[NZ] [me] (s|p|sp)|J [me] (s|p|sp)|(P\\+)?D [me] (s|p|sp)"); // NEW for French!!
private static final Pattern GN_FN = Pattern.compile("[NZ] [fe] (s|p|sp)|J [fe] (s|p|sp)|(P\\+)?D [fe] (s|p|sp)"); // NEW for French!!
//private static final Pattern NOM_ADJ = Pattern.compile("[NZ] *|J .*|V ppa .*");
private static final Pattern ADJECTIU = Pattern.compile("J .*|V ppa .*|PX.*");
private static final Pattern ADJECTIU_MS = Pattern.compile("J [me] (s|sp)|V ppa m s");
private static final Pattern ADJECTIU_FS = Pattern.compile("J [fe] (s|sp)|V ppa f s");
private static final Pattern ADJECTIU_MP = Pattern.compile("J [me] (p|sp)|V ppa m p");
private static final Pattern ADJECTIU_FP = Pattern.compile("J [fe] (p|sp)|V ppa f p");
private static final Pattern ADJECTIU_CP = Pattern.compile("J e (p|sp)");
private static final Pattern ADJECTIU_CS = Pattern.compile("J e (s|sp)");
private static final Pattern ADJECTIU_MN = Pattern.compile("J m sp"); // NEW for French!!
private static final Pattern ADJECTIU_FN = Pattern.compile("J f sp"); // NEW for French!!
private static final Pattern ADJECTIU_S = Pattern.compile("J .* (s|sp)|V ppa . s");
private static final Pattern ADJECTIU_P = Pattern.compile("J .* (p|sp)|V ppa . p");
private static final Pattern ADJECTIU_M = Pattern.compile("J [me] .*|V ppa [me] .*"); // NEW for French!!
private static final Pattern ADJECTIU_F = Pattern.compile("J [fe] .*|V ppa [fe] .*"); // NEW for French!!
private static final Pattern ADVERBI = Pattern.compile("A");
private static final Pattern CONJUNCIO = Pattern.compile("C .*");
private static final Pattern PUNTUACIO = Pattern.compile("_PUNCT");
private static final Pattern LOC_ADV = Pattern.compile("A");
private static final Pattern ADVERBIS_ACCEPTATS = Pattern.compile("A");
private static final Pattern COORDINACIO_IONI = Pattern.compile("et|ou|ni");
private static final Pattern KEEP_COUNT = Pattern.compile("Y|J .*|N .*|D .*|P.*|V ppa .*|M nonfin|UNKNOWN|Z.*|V.* inf|V ppr");
private static final Pattern KEEP_COUNT2 = Pattern.compile(",|et|ou|ni");
private static final Pattern STOP_COUNT = Pattern.compile("[;:\\(\\)\\[\\]–—―‒]");
private static final Pattern PREPOSICIONS = Pattern.compile("P");
private static final Pattern PREPOSICIO_CANVI_NIVELL = Pattern.compile("d'|de|des|du|à|au|aux|en|dans|sur|entre|par|pour|avec|sans|contre|comme");
private static final Pattern VERB = Pattern.compile("V.* (inf|ind|sub|con|ppr|imp).*"); // Any verb that is not V ppa
private static final Pattern INFINITIVE = Pattern.compile("V.* inf");
private static final Pattern GV = Pattern.compile("_GV_");
private static final FrenchSynthesizer synth = new FrenchSynthesizer(new French());
boolean adverbAppeared = false;
boolean conjunctionAppeared = false;
boolean punctuationAppeared = false;
boolean infinitiveAppeared = false;
@Override
public RuleMatch acceptRuleMatch(RuleMatch match, Map<String, String> arguments, int patternTokenPos,
AnalyzedTokenReadings[] patternTokens) throws IOException {
// int i = 0;
AnalyzedTokenReadings[] tokens = match.getSentence().getTokensWithoutWhitespace();
int i = patternTokenPos;
int j;
boolean isPlural = true;
boolean isPrevNoun = false;
Pattern substPattern = null;
Pattern gnPattern = null;
Pattern adjPattern = null;
boolean canBeMS = false;
boolean canBeFS = false;
boolean canBeMP = false;
boolean canBeFP = false;
boolean canBeP = false;
/* Count all nouns and determiners before the adjectives */
// Takes care of acceptable combinations.
int[] cNt = new int[maxLevels];
int[] cNMS = new int[maxLevels];
int[] cNFS = new int[maxLevels];
int[] cNMP = new int[maxLevels];
int[] cNMN = new int[maxLevels];
int[] cNFP = new int[maxLevels];
int[] cNCS = new int[maxLevels];
int[] cNCP = new int[maxLevels];
int[] cDMS = new int[maxLevels];
int[] cDFS = new int[maxLevels];
int[] cDMP = new int[maxLevels];
int[] cDFP = new int[maxLevels];
int[] cN = new int[maxLevels];
int[] cD = new int[maxLevels];
int level = 0;
j = 1;
initializeApparitions();
while (i - j > 0 && keepCounting(tokens[i - j]) && level < maxLevels) {
if (!isPrevNoun) {
if (matchPostagRegexp(tokens[i - j], NOM) || (
i - j - 1 > 0 && !matchPostagRegexp(tokens[i - j], NOM) && matchPostagRegexp(tokens[i - j], ADJECTIU)
&& matchPostagRegexp(tokens[i - j - 1], DET))) {
if (matchPostagRegexp(tokens[i - j], _GN_MS)) {
cNMS[level]++;
canBeMS = true;
}
if (matchPostagRegexp(tokens[i - j], _GN_FS)) {
cNFS[level]++;
canBeFS = true;
}
if (matchPostagRegexp(tokens[i - j], _GN_MP)) {
cNMP[level]++;
canBeMP = true;
}
if (matchPostagRegexp(tokens[i - j], _GN_FP)) {
cNFP[level]++;
canBeFP = true;
}
}
if (!matchPostagRegexp(tokens[i - j], _GN_)) {
if (matchPostagRegexp(tokens[i - j], NOM_MS)) {
cNMS[level]++;
canBeMS = true;
} else if (matchPostagRegexp(tokens[i - j], NOM_FS)) {
cNFS[level]++;
canBeFS = true;
} else if (matchPostagRegexp(tokens[i - j], NOM_MP)) {
cNMP[level]++;
canBeMP = true;
} else if (matchPostagRegexp(tokens[i - j], NOM_MN)) {
cNMN[level]++;
canBeMS = true;
canBeMP = true;
} else if (matchPostagRegexp(tokens[i - j], NOM_FP)) {
cNFP[level]++;
canBeFP = true;
} else if (matchPostagRegexp(tokens[i - j], NOM_CS)) {
cNCS[level]++;
canBeMS = true;
canBeFS = true;
} else if (matchPostagRegexp(tokens[i - j], NOM_CP)) {
cNCP[level]++;
canBeFP = true;
canBeMP = true;
}
}
}
// avoid two consecutive nouns
if (matchPostagRegexp(tokens[i - j], NOM)) {
cNt[level]++;
isPrevNoun = true;
// initializeApparitions();
} else {
isPrevNoun = false;
}
if (matchPostagRegexp(tokens[i - j], DET_CS)) {
if (matchPostagRegexp(tokens[i - j + 1], NOM_MS)) {
cDMS[level]++;
canBeMS = true;
}
if (matchPostagRegexp(tokens[i - j + 1], NOM_FS)) {
cDFS[level]++;
canBeFS = true;
}
}
if (matchPostagRegexp(tokens[i - j], DET_CP)) {
if (matchPostagRegexp(tokens[i - j + 1], NOM_MP)) {
cDMS[level]++;
canBeMP = true;
}
if (matchPostagRegexp(tokens[i - j + 1], NOM_FP)) {
cDFS[level]++;
canBeFP = true;
}
}
//TODO DET_CS, DET_CP without noun afterwards
if (!matchPostagRegexp(tokens[i - j], ADVERBI)) {
if (matchPostagRegexp(tokens[i - j], DET_MS)) {
cDMS[level]++;
canBeMS = true;
}
if (matchPostagRegexp(tokens[i - j], DET_FS)) {
cDFS[level]++;
canBeFS = true;
}
if (matchPostagRegexp(tokens[i - j], DET_MP)) {
cDMP[level]++;
canBeMP = true;
}
if (matchPostagRegexp(tokens[i - j], DET_FP)) {
cDFP[level]++;
canBeFP = true;
}
}
if (i - j - 1 > 0) {
if (matchRegexp(tokens[i - j].getToken(), PREPOSICIO_CANVI_NIVELL)
&& !matchPostagRegexp(tokens[i - j], CONJUNCIO)
&& !matchRegexp(tokens[i - j - 1].getToken(), COORDINACIO_IONI)
&& !matchPostagRegexp(tokens[i - j + 1], ADVERBI)) {
level++;
}
}
j = updateJValue(tokens, i, j, level);
updateApparitions(tokens[i - j]);
j++;
}
level++;
if (level > maxLevels) {
level = maxLevels;
}
j = 0;
int cNtotal = 0;
int cDtotal = 0;
while (j < level) {
cN[j] = cNMS[j] + cNFS[j] + cNMP[j] + cNFP[j] + cNCS[j] + cNCP[j] + cNMN[j];
cD[j] = cDMS[j] + cDFS[j] + cDMP[j] + cDFP[j];
cNtotal += cN[j];
cDtotal += cD[j];
// exceptions: adjective is plural and there are several nouns before
if (matchPostagRegexp(tokens[i], ADJECTIU_MP) && (cN[j] > 1 || cD[j] > 1)
&& (cNMS[j] + cNMN[j] + cNMP[j] + cNCS[j] + cNCP[j] + cDMS[j] + cDMP[j]) > 0
&& (cNFS[j] + cNFP[j] <= cNt[j])) {
return null;
}
if (matchPostagRegexp(tokens[i], ADJECTIU_FP) && (cN[j] > 1 || cD[j] > 1)
&& ((cNMS[j] + cNMP[j] + cNMN[j] + cDMS[j] + cDMP[j]) == 0 || (cNt[j] > 0 && cNFS[j] + cNFP[j] >= cNt[j]))) {
return null;
}
// Adjective can't be singular
if (cN[j] + cD[j] > 0) { // && level>1
isPlural = isPlural && cD[j] > 1 && level>1; // cN[j]>1
canBeP = canBeP || cN[j]>1;
}
j++;
}
// there is no noun, (no determinant --> && cDtotal==0)
if (cNtotal == 0 && cDtotal == 0) {
return null;
}
// patterns according to the analyzed adjective
if (matchPostagRegexp(tokens[i], ADJECTIU_CS)) {
substPattern = GN_CS;
adjPattern = ADJECTIU_S;
gnPattern = _GN_CS;
} else if (matchPostagRegexp(tokens[i], ADJECTIU_CP)) {
substPattern = GN_CP;
adjPattern = ADJECTIU_P;
gnPattern = _GN_CP;
} else if (matchPostagRegexp(tokens[i], ADJECTIU_MN)) {
substPattern = GN_MN;
adjPattern = ADJECTIU_M;
gnPattern = _GN_MN;
} else if (matchPostagRegexp(tokens[i], ADJECTIU_FN)) {
substPattern = GN_FN;
adjPattern = ADJECTIU_FN;
gnPattern = _GN_FN;
} else if (matchPostagRegexp(tokens[i], ADJECTIU_MS)) {
substPattern = GN_MS;
adjPattern = ADJECTIU_MS;
gnPattern = _GN_MS;
} else if (matchPostagRegexp(tokens[i], ADJECTIU_FS)) {
substPattern = GN_FS;
adjPattern = ADJECTIU_FS;
gnPattern = _GN_FS;
} else if (matchPostagRegexp(tokens[i], ADJECTIU_MP)) {
substPattern = GN_MP;
adjPattern = ADJECTIU_MP;
gnPattern = _GN_MP;
} else if (matchPostagRegexp(tokens[i], ADJECTIU_FP)) {
substPattern = GN_FP;
adjPattern = ADJECTIU_FP;
gnPattern = _GN_FP;
}
if (substPattern == null || gnPattern == null || adjPattern == null) {
return null;
}
// combinations Det/Nom + adv (1,2..) + adj.
// If there is agreement, the rule doesn't match
j = 1;
boolean keepCount = true;
while (i - j > 0 && keepCount) {
if (matchPostagRegexp(tokens[i - j], NOM_DET) && matchPostagRegexp(tokens[i - j], gnPattern)) {
return null; // there is a previous agreeing noun
} else if (!matchPostagRegexp(tokens[i - j], _GN_) && matchPostagRegexp(tokens[i - j], substPattern)) {
return null; // there is a previous agreeing noun
}
keepCount = !matchPostagRegexp(tokens[i - j], NOM_DET);
j++;
}
// Necessary condition: previous token is a non-agreeing noun
// or it is adjective or adverb (not preceded by verb)
// /*&& !matchPostagRegexp(tokens[i],NOM)*/
if ( (matchPostagRegexp(tokens[i - 1], NOM) && !matchPostagRegexp(tokens[i - 1], substPattern))
|| (matchPostagRegexp(tokens[i - 1], _GN_) && !matchPostagRegexp(tokens[i - 1], gnPattern))
|| (matchPostagRegexp(tokens[i - 1], ADJECTIU) && !matchPostagRegexp(tokens[i - 1], adjPattern))
|| (i > 2 && matchPostagRegexp(tokens[i - 1], ADVERBIS_ACCEPTATS) && !matchPostagRegexp(tokens[i - 2], VERB)
&& !matchPostagRegexp(tokens[i - 2], PREPOSICIONS))
|| (i > 3 && matchPostagRegexp(tokens[i - 1], LOC_ADV) && matchPostagRegexp(tokens[i - 2], LOC_ADV)
&& !matchPostagRegexp(tokens[i - 3], VERB) && !matchPostagRegexp(tokens[i - 3], PREPOSICIONS))) {
} else {
return null;
}
// Adjective can't be singular. The rule matches
if (!(isPlural && matchPostagRegexp(tokens[i], ADJECTIU_S))) {
// look into previous words
j = 1;
initializeApparitions();
while (i - j > 0 && keepCounting(tokens[i - j]) && (level > 1 || j < 4)) {
// there is a previous agreeing noun
if (!matchPostagRegexp(tokens[i - j], _GN_) && matchPostagRegexp(tokens[i - j], NOM_DET)
&& matchPostagRegexp(tokens[i - j], substPattern)) {
return null;
// there is a previous agreeing adjective (in a nominal group)
} else if (matchPostagRegexp(tokens[i - j], gnPattern)) {
return null;
// if there is no nominal group, it requires noun
} /*
* else if (!matchPostagRegexp(tokens[i - j], _GN_) &&
* matchPostagRegexp(tokens[i - j], substPattern)) { return null; // there is a
* previous agreeing noun }
*/
j = updateJValue(tokens, i, j, 0);
updateApparitions(tokens[i - j]);
j++;
}
}
// The rule matches
// Synthesize suggestions
List<String> suggestions = new ArrayList<>();
AnalyzedToken at = getAnalyzedToken(tokens[patternTokenPos], ADJECTIU_CS);
if (at != null) {
suggestions.addAll(Arrays.asList(synth.synthesize(at,"J e p", true)));
}
if (suggestions.isEmpty()) {
at = getAnalyzedToken(tokens[patternTokenPos], ADJECTIU_CP);
if (at != null) {
suggestions.addAll(Arrays.asList(synth.synthesize(at,"J e s", true)));
}
}
if (suggestions.isEmpty() && isPlural) {
at = getAnalyzedToken(tokens[patternTokenPos], ADJECTIU_P);
if (at != null) {
suggestions.addAll(Arrays.asList(synth.synthesize(at, "J . p|V ppa . p", true)));
}
}
at = getAnalyzedToken(tokens[patternTokenPos], ADJECTIU);
if (at != null && suggestions.isEmpty()) {
if (canBeMS && !isPlural) {
suggestions.addAll(Arrays.asList(synth.synthesize(at, "J m s|V ppa m s", true)));
}
if (canBeFS && !isPlural) {
suggestions.addAll(Arrays.asList(synth.synthesize(at, "J f s|V ppa f s", true)));
}
if (canBeMP) {
suggestions.addAll(Arrays.asList(synth.synthesize(at, "J m p|V ppa m p", true)));
}
if (canBeFP) {
suggestions.addAll(Arrays.asList(synth.synthesize(at, "J f p|V ppa f p", true)));
}
if (canBeMS && (isPlural || canBeP)) {
suggestions.addAll(Arrays.asList(synth.synthesize(at, "J m p|V ppa m p", true)));
}
if (canBeFS && !canBeMS && (isPlural || canBeP)) {
suggestions.addAll(Arrays.asList(synth.synthesize(at, "J f p|V ppa f p", true)));
}
}
//set suggestion removing duplicates
suggestions = suggestions.stream().distinct().collect(Collectors.toList());
// avoid the original token as suggestion
if (suggestions.contains(tokens[patternTokenPos].getToken().toLowerCase())) {
suggestions.remove(tokens[patternTokenPos].getToken().toLowerCase());
}
match.setSuggestedReplacements(suggestions);
return match;
}
private int updateJValue(AnalyzedTokenReadings[] tokens, int i, int j, int level) {
/* if (level > 0 && matchRegexp(tokens[i - j].getToken(), COORDINACIO_IONI)) {
int k = 1;
while (k < 4 && i - j - k > 0
&& (matchPostagRegexp(tokens[i - j - k], KEEP_COUNT)
|| matchRegexp(tokens[i - j - k].getToken(), KEEP_COUNT2)
|| matchPostagRegexp(tokens[i - j - k], ADVERBIS_ACCEPTATS))
&& (!matchRegexp(tokens[i - j - k].getToken(), STOP_COUNT))) {
if (matchPostagRegexp(tokens[i - j - k], PREPOSICIONS)) {
j = j + k;
break;
}
k++;
}
}*/
// deux ou plus
if (matchRegexp(tokens[i - j].getToken(), COORDINACIO_IONI)) {
if (i - j - 1 > 0 && i - j + 1 < tokens.length) {
if (matchPostagRegexp(tokens[i - j - 1], DET) && tokens[i - j + 1].getToken().equals("plus")) {
j = j + 1;
}
}
}
return j;
}
private boolean keepCounting(AnalyzedTokenReadings aTr) {
if (matchRegexp(aTr.getToken(), PREPOSICIO_CANVI_NIVELL)) {
return true;
}
if (aTr.getToken().equals(".")) { //it is not sentence end, but abbreviation
return true;
}
// stop searching if there is some of these combinations:
// adverb+comma, adverb+conjunction, comma+conjunction,
// punctuation+punctuation
if ((adverbAppeared && conjunctionAppeared) || (adverbAppeared && punctuationAppeared)
|| (conjunctionAppeared && punctuationAppeared) || (punctuationAppeared && matchPostagRegexp(aTr, PUNTUACIO))
|| (infinitiveAppeared && matchRegexp(aTr.getToken(), COORDINACIO_IONI))
|| (infinitiveAppeared && adverbAppeared)) {
return false;
}
return (matchPostagRegexp(aTr, KEEP_COUNT) || matchRegexp(aTr.getToken(), KEEP_COUNT2)
|| matchPostagRegexp(aTr, ADVERBIS_ACCEPTATS)) && !matchRegexp(aTr.getToken(), STOP_COUNT)
&& (!matchPostagRegexp(aTr, GV) || matchPostagRegexp(aTr, _GN_));
}
private void initializeApparitions() {
adverbAppeared = false;
conjunctionAppeared = false;
punctuationAppeared = false;
infinitiveAppeared = false;
}
private void updateApparitions(AnalyzedTokenReadings aTr) {
conjunctionAppeared |= matchPostagRegexp(aTr, CONJUNCIO);
if (aTr.getToken().equals("com")) {
return;
}
if (matchPostagRegexp(aTr, NOM) || matchPostagRegexp(aTr, ADJECTIU)) {
initializeApparitions();
return;
}
adverbAppeared |= matchPostagRegexp(aTr, ADVERBI);
punctuationAppeared |= (matchPostagRegexp(aTr, PUNTUACIO) || aTr.getToken().equals(","));
infinitiveAppeared |= matchPostagRegexp(aTr, INFINITIVE);
}
/**
* Match POS tag with regular expression
*/
private boolean matchPostagRegexp(AnalyzedTokenReadings aToken, Pattern pattern) {
boolean matches = false;
for (AnalyzedToken analyzedToken : aToken) {
String posTag = analyzedToken.getPOSTag();
if (posTag == null) {
posTag = "UNKNOWN";
}
final Matcher m = pattern.matcher(posTag);
if (m.matches()) {
matches = true;
break;
}
}
return matches;
}
/**
* Match String with regular expression
*/
private boolean matchRegexp(String s, Pattern pattern) {
final Matcher m = pattern.matcher(s);
return m.matches();
}
private AnalyzedToken getAnalyzedToken(AnalyzedTokenReadings aToken, Pattern pattern) {
for (AnalyzedToken analyzedToken : aToken) {
String posTag = analyzedToken.getPOSTag();
if (posTag == null) {
posTag = "UNKNOWN";
}
final Matcher m = pattern.matcher(posTag);
if (m.matches()) {
return analyzedToken;
}
}
return null;
}
}
|
package org.safehaus.subutai.core.tracker.impl;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;
import org.safehaus.subutai.common.tracker.ProductOperation;
import org.safehaus.subutai.common.tracker.ProductOperationState;
import org.safehaus.subutai.common.tracker.ProductOperationView;
import org.safehaus.subutai.core.db.api.DBException;
import org.safehaus.subutai.core.db.api.DbManager;
import org.safehaus.subutai.core.tracker.api.Tracker;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.datastax.driver.core.ResultSet;
import com.datastax.driver.core.Row;
import com.google.common.base.Preconditions;
import com.google.common.base.Strings;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonSyntaxException;
/**
* This is an implementation of Tracker
*/
public class TrackerImpl implements Tracker
{
/**
* Used to serialize/deserialize product operation to/from json format
*/
private static final Gson GSON = new GsonBuilder().setPrettyPrinting().disableHtmlEscaping().create();
private static final Logger LOG = LoggerFactory.getLogger( TrackerImpl.class.getName() );
private static final String SOURCE_IS_EMPTY_MSG = "Source is null or empty";
/**
* reference to dbmanager
*/
private DbManager dbManager;
public void setDbManager( DbManager dbManager )
{
Preconditions.checkNotNull( dbManager, "Db manager is null" );
this.dbManager = dbManager;
}
/**
* Get view of product operation by operation id
*
* @param source - source of product operation, usually this is a module name
* @param operationTrackId - id of operation
*
* @return - product operation view
*/
public ProductOperationView getProductOperation( String source, UUID operationTrackId )
{
Preconditions.checkArgument( !Strings.isNullOrEmpty( source ), SOURCE_IS_EMPTY_MSG );
Preconditions.checkNotNull( operationTrackId, "Operation track id is null" );
try
{
ResultSet rs = dbManager.executeQuery2( "select info from product_operation where source = ? and id = ?",
source.toLowerCase(), operationTrackId );
return constructProductOperation( rs.one() );
}
catch ( DBException | JsonSyntaxException ex )
{
LOG.error( "Error in getProductOperation", ex );
}
return null;
}
private ProductOperationViewImpl constructProductOperation( Row row )
{
if ( row != null )
{
String info = row.getString( "info" );
ProductOperationImpl po = GSON.fromJson( info, ProductOperationImpl.class );
return new ProductOperationViewImpl( po );
}
return null;
}
/**
* Saves product operation o DB
*
* @param source - source of product operation, usually this is a module
* @param po - product operation
*
* @return - true if all went well, false otherwise
*/
boolean saveProductOperation( String source, ProductOperationImpl po )
{
Preconditions.checkArgument( !Strings.isNullOrEmpty( source ), SOURCE_IS_EMPTY_MSG );
Preconditions.checkNotNull( po, "Product operation is null" );
try
{
dbManager.executeUpdate2( "insert into product_operation(source,id,info) values(?,?,?)",
source.toLowerCase(), po.getId(), GSON.toJson( po ) );
return true;
}
catch ( DBException e )
{
LOG.error( "Error in saveProductOperation", e );
}
return false;
}
/**
* Creates product operation and save it to DB
*
* @param source - source of product operation, usually this is a module
* @param description - description of operation
*
* @return - returns created product operation
*/
public ProductOperation createProductOperation( String source, String description )
{
Preconditions.checkArgument( !Strings.isNullOrEmpty( source ), SOURCE_IS_EMPTY_MSG );
Preconditions.checkNotNull( !Strings.isNullOrEmpty( description ), "Description is null or empty" );
ProductOperationImpl po = new ProductOperationImpl( source.toLowerCase(), description, this );
if ( saveProductOperation( source, po ) )
{
return po;
}
return null;
}
/**
* Returns list of product operations (views) filtering them by date interval
*
* @param source - source of product operation, usually this is a module
* @param fromDate - beginning date of filter
* @param toDate - ending date of filter
* @param limit - limit of records to return
*
* @return - list of product operation views
*/
public List<ProductOperationView> getProductOperations( String source, Date fromDate, Date toDate, int limit )
{
Preconditions.checkArgument( limit > 0, "Limit must be greater than 0" );
Preconditions.checkArgument( !Strings.isNullOrEmpty( source ), SOURCE_IS_EMPTY_MSG );
Preconditions.checkNotNull( fromDate, "From Date is null" );
Preconditions.checkNotNull( toDate, "To Date is null" );
List<ProductOperationView> list = new ArrayList<>();
try
{
ResultSet rs = dbManager.executeQuery2(
"select info from product_operation where source = ?" + " and id >= maxTimeuuid(?)"
+ " and id <= minTimeuuid(?)" + " order by id desc limit ?", source.toLowerCase(), fromDate,
toDate, limit );
for ( Row row : rs )
{
ProductOperationViewImpl productOperationViewImpl = constructProductOperation( row );
if ( row != null )
{
list.add( productOperationViewImpl );
}
}
}
catch ( DBException | JsonSyntaxException ex )
{
LOG.error( "Error in getProductOperations", ex );
}
return list;
}
/**
* Returns list of all sources of product operations for which product operations exist in DB
*
* @return list of product operation sources
*/
public List<String> getProductOperationSources()
{
List<String> sources = new ArrayList<>();
try
{
ResultSet rs = dbManager.executeQuery2( "select distinct source from product_operation" );
for ( Row row : rs )
{
String source = row.getString( "source" );
if ( !Strings.isNullOrEmpty( source ) )
{
sources.add( source.toLowerCase() );
}
}
}
catch ( DBException e )
{
LOG.error( "Error in getProductOperationSources", e );
}
return sources;
}
/**
* Prints log of product operation to std out stream
*
* @param operationTrackId - id of operation
* @param maxOperationDurationMs - max operation duration timeout after which printing ceases
*/
@Override
public void printOperationLog( String source, UUID operationTrackId, long maxOperationDurationMs )
{
int logSize = 0;
long startedTs = System.currentTimeMillis();
while ( !Thread.interrupted() )
{
ProductOperationView po = getProductOperation( source.toLowerCase(), operationTrackId );
if ( po != null )
{
//print log if anything new is appended to it
if ( logSize != po.getLog().length() )
{
LOG.info( po.getLog().substring( logSize, po.getLog().length() ) );
logSize = po.getLog().length();
}
//return if operation is completed
//or if time limit is reached
if ( po.getState() != ProductOperationState.RUNNING || System.currentTimeMillis() - startedTs > maxOperationDurationMs)
{
return;
}
try
{
Thread.sleep( 100 );
}
catch ( InterruptedException e )
{
return;
}
}
else
{
LOG.warn( "Product operation not found" );
return;
}
}
}
}
|
package org.laladev.moneyjinn.server.controller.capitalsource;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;
import javax.inject.Inject;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.laladev.moneyjinn.core.error.ErrorCode;
import org.laladev.moneyjinn.core.rest.model.ErrorResponse;
import org.laladev.moneyjinn.core.rest.model.capitalsource.CreateCapitalsourceRequest;
import org.laladev.moneyjinn.core.rest.model.capitalsource.CreateCapitalsourceResponse;
import org.laladev.moneyjinn.core.rest.model.transport.CapitalsourceTransport;
import org.laladev.moneyjinn.core.rest.model.transport.ValidationItemTransport;
import org.laladev.moneyjinn.model.access.GroupID;
import org.laladev.moneyjinn.model.access.UserID;
import org.laladev.moneyjinn.model.capitalsource.Capitalsource;
import org.laladev.moneyjinn.model.capitalsource.CapitalsourceID;
import org.laladev.moneyjinn.model.capitalsource.CapitalsourceState;
import org.laladev.moneyjinn.model.capitalsource.CapitalsourceType;
import org.laladev.moneyjinn.server.builder.CapitalsourceTransportBuilder;
import org.laladev.moneyjinn.server.builder.GroupTransportBuilder;
import org.laladev.moneyjinn.server.builder.UserTransportBuilder;
import org.laladev.moneyjinn.server.builder.ValidationItemTransportBuilder;
import org.laladev.moneyjinn.server.controller.AbstractControllerTest;
import org.laladev.moneyjinn.service.api.IAccessRelationService;
import org.laladev.moneyjinn.service.api.ICapitalsourceService;
import org.springframework.http.HttpMethod;
import org.springframework.test.context.jdbc.Sql;
public class CreateCapitalsourceTest extends AbstractControllerTest {
@Inject
ICapitalsourceService capitalsourceService;
@Inject
IAccessRelationService accessRelationService;
private final HttpMethod method = HttpMethod.POST;
private String userName;
private String userPassword;
@Before
public void setUp() {
this.userName = UserTransportBuilder.USER1_NAME;
this.userPassword = UserTransportBuilder.USER1_PASSWORD;
}
@Override
protected String getUsername() {
return this.userName;
}
@Override
protected String getPassword() {
return this.userPassword;
}
@Override
protected String getUsecase() {
return super.getUsecaseFromTestClassName(this.getClass());
}
private void testError(final CapitalsourceTransport transport, final ErrorCode errorCode) throws Exception {
final CreateCapitalsourceRequest request = new CreateCapitalsourceRequest();
request.setCapitalsourceTransport(transport);
final List<ValidationItemTransport> validationItems = new ArrayList<>();
validationItems
.add(new ValidationItemTransportBuilder().withKey(null).withError(errorCode.getErrorCode()).build());
final CreateCapitalsourceResponse expected = new CreateCapitalsourceResponse();
expected.setValidationItemTransports(validationItems);
expected.setResult(Boolean.FALSE);
final CreateCapitalsourceResponse actual = super.callUsecaseWithContent("", this.method, request, false,
CreateCapitalsourceResponse.class);
Assert.assertEquals(expected, actual);
}
@Test
public void test_CapitalsourcenameAlreadyExisting_Error() throws Exception {
final CapitalsourceTransport transport = new CapitalsourceTransportBuilder().forNewCapitalsource().build();
transport.setComment(CapitalsourceTransportBuilder.CAPITALSOURCE1_COMMENT);
this.testError(transport, ErrorCode.NAME_ALREADY_EXISTS);
}
@Test
public void test_emptyCapitalsourcename_Error() throws Exception {
final CapitalsourceTransport transport = new CapitalsourceTransportBuilder().forNewCapitalsource().build();
transport.setComment("");
this.testError(transport, ErrorCode.COMMENT_IS_NOT_SET);
}
@Test
public void test_nullCapitalsourcename_Error() throws Exception {
final CapitalsourceTransport transport = new CapitalsourceTransportBuilder().forNewCapitalsource().build();
transport.setComment(null);
this.testError(transport, ErrorCode.COMMENT_IS_NOT_SET);
}
@Test
public void test_ToLongAccountnumber_Error() throws Exception {
final CapitalsourceTransport transport = new CapitalsourceTransportBuilder().forNewCapitalsource().build();
transport.setAccountNumber("12345678901234567890123456789012345");
this.testError(transport, ErrorCode.ACCOUNT_NUMBER_TO_LONG);
}
@Test
public void test_ToLongBankcode_Error() throws Exception {
final CapitalsourceTransport transport = new CapitalsourceTransportBuilder().forNewCapitalsource().build();
transport.setBankCode("123456789012");
this.testError(transport, ErrorCode.BANK_CODE_TO_LONG);
}
@Test
public void test_AccountnumberInvalidChar_Error() throws Exception {
final CapitalsourceTransport transport = new CapitalsourceTransportBuilder().forNewCapitalsource().build();
transport.setAccountNumber("+");
this.testError(transport, ErrorCode.ACCOUNT_NUMBER_CONTAINS_ILLEGAL_CHARS);
}
@Test
public void test_BankcodeInvalidChar_Error() throws Exception {
final CapitalsourceTransport transport = new CapitalsourceTransportBuilder().forNewCapitalsource().build();
transport.setBankCode("+");
this.testError(transport, ErrorCode.BANK_CODE_CONTAINS_ILLEGAL_CHARS);
}
@Test
public void test_standardRequest_SuccessfullNoContent() throws Exception {
final CreateCapitalsourceRequest request = new CreateCapitalsourceRequest();
final CapitalsourceTransport transport = new CapitalsourceTransportBuilder().forNewCapitalsource().build();
request.setCapitalsourceTransport(transport);
final CreateCapitalsourceResponse expected = new CreateCapitalsourceResponse();
expected.setCapitalsourceId(CapitalsourceTransportBuilder.NEXT_ID);
final CreateCapitalsourceResponse actual = super.callUsecaseWithContent("", this.method, request, false,
CreateCapitalsourceResponse.class);
Assert.assertEquals(expected, actual);
final UserID userId = new UserID(UserTransportBuilder.USER1_ID);
final GroupID groupId = new GroupID(GroupTransportBuilder.GROUP1_ID);
final CapitalsourceID capitalsourceId = new CapitalsourceID(CapitalsourceTransportBuilder.NEXT_ID);
final Capitalsource capitalsource = this.capitalsourceService.getCapitalsourceById(userId, groupId,
capitalsourceId);
Assert.assertEquals(CapitalsourceTransportBuilder.NEXT_ID, capitalsource.getId().getId());
Assert.assertEquals(CapitalsourceTransportBuilder.NEWCAPITALSOURCE_COMMENT, capitalsource.getComment());
}
@Test
public void test_Bic8Digits_fillesUpTo11Digits() throws Exception {
final CreateCapitalsourceRequest request = new CreateCapitalsourceRequest();
final CapitalsourceTransport transport = new CapitalsourceTransportBuilder().forNewCapitalsource().build();
transport.setBankCode("ABCDEFGH");
request.setCapitalsourceTransport(transport);
final CreateCapitalsourceResponse expected = new CreateCapitalsourceResponse();
expected.setCapitalsourceId(CapitalsourceTransportBuilder.NEXT_ID);
final CreateCapitalsourceResponse actual = super.callUsecaseWithContent("", this.method, request, false,
CreateCapitalsourceResponse.class);
Assert.assertEquals(expected, actual);
final UserID userId = new UserID(UserTransportBuilder.USER1_ID);
final GroupID groupId = new GroupID(GroupTransportBuilder.GROUP1_ID);
final CapitalsourceID capitalsourceId = new CapitalsourceID(CapitalsourceTransportBuilder.NEXT_ID);
final Capitalsource capitalsource = this.capitalsourceService.getCapitalsourceById(userId, groupId,
capitalsourceId);
Assert.assertEquals(CapitalsourceTransportBuilder.NEXT_ID, capitalsource.getId().getId());
Assert.assertEquals(CapitalsourceTransportBuilder.NEWCAPITALSOURCE_COMMENT, capitalsource.getComment());
Assert.assertEquals(transport.getBankCode() + "XXX", capitalsource.getBankAccount().getBankCode());
}
@Test
public void test_differentUserIdSet_ButIgnoredAndAlwaysCreatedWithOwnUserId() throws Exception {
final CreateCapitalsourceRequest request = new CreateCapitalsourceRequest();
final CapitalsourceTransport transport = new CapitalsourceTransportBuilder().forNewCapitalsource().build();
transport.setUserid(UserTransportBuilder.ADMIN_ID);
request.setCapitalsourceTransport(transport);
final CreateCapitalsourceResponse expected = new CreateCapitalsourceResponse();
expected.setCapitalsourceId(CapitalsourceTransportBuilder.NEXT_ID);
final CreateCapitalsourceResponse actual = super.callUsecaseWithContent("", this.method, request, false,
CreateCapitalsourceResponse.class);
Assert.assertEquals(expected, actual);
final UserID userId = new UserID(UserTransportBuilder.USER1_ID);
final GroupID groupId = new GroupID(GroupTransportBuilder.GROUP1_ID);
final CapitalsourceID capitalsourceId = new CapitalsourceID(CapitalsourceTransportBuilder.NEXT_ID);
final Capitalsource capitalsource = this.capitalsourceService.getCapitalsourceById(userId, groupId,
capitalsourceId);
Assert.assertEquals(CapitalsourceTransportBuilder.NEXT_ID, capitalsource.getId().getId());
Assert.assertEquals(CapitalsourceTransportBuilder.NEWCAPITALSOURCE_COMMENT, capitalsource.getComment());
}
@Test
public void test_checkDefaults_SuccessfullNoContent() throws Exception {
final CreateCapitalsourceRequest request = new CreateCapitalsourceRequest();
final CapitalsourceTransport transport = new CapitalsourceTransportBuilder().forNewCapitalsource().build();
transport.setValidFrom(null);
transport.setValidTil(null);
transport.setState(null);
transport.setType(null);
transport.setAccountNumber(null);
transport.setBankCode(null);
request.setCapitalsourceTransport(transport);
final CreateCapitalsourceResponse expected = new CreateCapitalsourceResponse();
expected.setCapitalsourceId(CapitalsourceTransportBuilder.NEXT_ID);
final CreateCapitalsourceResponse actual = super.callUsecaseWithContent("", this.method, request, false,
CreateCapitalsourceResponse.class);
Assert.assertEquals(expected, actual);
final UserID userId = new UserID(UserTransportBuilder.USER1_ID);
final GroupID groupId = new GroupID(GroupTransportBuilder.GROUP1_ID);
final CapitalsourceID capitalsourceId = new CapitalsourceID(CapitalsourceTransportBuilder.NEXT_ID);
final Capitalsource capitalsource = this.capitalsourceService.getCapitalsourceById(userId, groupId,
capitalsourceId);
Assert.assertEquals(CapitalsourceTransportBuilder.NEXT_ID, capitalsource.getId().getId());
Assert.assertEquals(CapitalsourceTransportBuilder.NEWCAPITALSOURCE_COMMENT, capitalsource.getComment());
Assert.assertEquals(CapitalsourceState.CACHE, capitalsource.getState());
Assert.assertEquals(CapitalsourceType.CURRENT_ASSET, capitalsource.getType());
Assert.assertEquals(LocalDate.now(), capitalsource.getValidFrom());
Assert.assertEquals(LocalDate.parse("2999-12-31"), capitalsource.getValidTil());
Assert.assertNull(capitalsource.getBankAccount());
}
@Test
public void test_AuthorizationRequired_Error() throws Exception {
this.userName = null;
this.userPassword = null;
final ErrorResponse actual = super.callUsecaseWithoutContent("", this.method, false, ErrorResponse.class);
Assert.assertEquals(super.accessDeniedErrorResponse(), actual);
}
@Test
@Sql("classpath:h2defaults.sql")
public void test_emptyDatabase_noException() throws Exception {
this.userName = UserTransportBuilder.ADMIN_NAME;
this.userPassword = UserTransportBuilder.ADMIN_PASSWORD;
final CreateCapitalsourceRequest request = new CreateCapitalsourceRequest();
final CapitalsourceTransport transport = new CapitalsourceTransportBuilder().forNewCapitalsource().build();
request.setCapitalsourceTransport(transport);
final CreateCapitalsourceResponse expected = new CreateCapitalsourceResponse();
expected.setCapitalsourceId(1L);
final CreateCapitalsourceResponse actual = super.callUsecaseWithContent("", this.method, request, false,
CreateCapitalsourceResponse.class);
Assert.assertEquals(expected, actual);
final UserID userId = new UserID(UserTransportBuilder.ADMIN_ID);
final GroupID groupId = new GroupID(GroupTransportBuilder.ADMINGROUP_ID);
final CapitalsourceID capitalsourceId = new CapitalsourceID(1l);
final Capitalsource capitalsource = this.capitalsourceService.getCapitalsourceById(userId, groupId,
capitalsourceId);
Assert.assertEquals(new Long(1l), capitalsource.getId().getId());
Assert.assertEquals(CapitalsourceTransportBuilder.NEWCAPITALSOURCE_COMMENT, capitalsource.getComment());
}
}
|
package com.planetmayo.debrief.satc.model.contributions;
import java.awt.geom.Point2D;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import org.eclipse.core.runtime.Status;
import com.planetmayo.debrief.satc.model.GeoPoint;
import com.planetmayo.debrief.satc.model.generator.IContributions;
import com.planetmayo.debrief.satc.model.legs.CoreRoute;
import com.planetmayo.debrief.satc.model.legs.LegType;
import com.planetmayo.debrief.satc.model.states.BaseRange.IncompatibleStateException;
import com.planetmayo.debrief.satc.model.states.BoundedState;
import com.planetmayo.debrief.satc.model.states.LocationRange;
import com.planetmayo.debrief.satc.model.states.ProblemSpace;
import com.planetmayo.debrief.satc.model.states.State;
import com.planetmayo.debrief.satc.util.GeoSupport;
import com.planetmayo.debrief.satc.util.MathUtils;
import com.planetmayo.debrief.satc.util.ObjectUtils;
import com.planetmayo.debrief.satc.util.calculator.GeodeticCalculator;
import com.planetmayo.debrief.satc.zigdetector.ILegStorer;
import com.planetmayo.debrief.satc.zigdetector.LegOfData;
import com.planetmayo.debrief.satc.zigdetector.OwnshipLegDetector;
import com.planetmayo.debrief.satc.zigdetector.Sensor;
import com.planetmayo.debrief.satc.zigdetector.ZigDetector;
import com.planetmayo.debrief.satc_rcp.SATC_Activator;
import com.vividsolutions.jts.geom.Coordinate;
import com.vividsolutions.jts.geom.GeometryFactory;
import com.vividsolutions.jts.geom.LineString;
import com.vividsolutions.jts.geom.LinearRing;
import com.vividsolutions.jts.geom.Polygon;
import com.vividsolutions.jts.geom.impl.CoordinateArraySequence;
public class BearingMeasurementContribution extends
CoreMeasurementContribution<BearingMeasurementContribution.BMeasurement>
{
private static final long serialVersionUID = 1L;
public static final String BEARING_ERROR = "bearingError";
public static final String RUN_MDA = "autoDetect";
public static interface MDAResultsListener{
public void sliced(String string, List<LegOfData> ownshipLegs,
ArrayList<StraightLegForecastContribution> arrayList,
ArrayList<HostState> hostStates);
}
/**
* the allowable bearing error (in radians)
*
*/
private Double bearingError = 0d;
/**
* flag for whether this contribution should run an MDA on the data
*
*/
private boolean runMDA = true;
/** store the ownship states, if possible. We use this to run the
* manoeuvre detection algorithm
*/
private ArrayList<HostState> states;
/** array of listeners interested in MDA
*
*/
private transient ArrayList<MDAResultsListener> _listeners = null;
@Override
public void actUpon(ProblemSpace space) throws IncompatibleStateException
{
// ok, here we really go for it!
Iterator<BMeasurement> iter = measurements.iterator();
// sort out a geometry factory
GeometryFactory factory = GeoSupport.getFactory();
while (iter.hasNext())
{
BearingMeasurementContribution.BMeasurement measurement = iter.next();
// is it active?
if (measurement.isActive())
{
// ok, create the polygon for this measurement
GeoPoint origin = measurement.origin;
double bearing = measurement.bearingAngle;
double range = measurement.range;
// sort out the left/right edges
double leftEdge = bearing - bearingError;
double rightEdge = bearing + bearingError;
// ok, generate the polygon
Coordinate[] coords = new Coordinate[5];
// start off with the origin
final double lon = origin.getLon();
final double lat = origin.getLat();
coords[0] = new Coordinate(lon, lat);
// create a utility object to help with calcs
GeodeticCalculator calc = GeoSupport.createCalculator();
// now the top-left
calc.setStartingGeographicPoint(new Point2D.Double(lon, lat));
calc.setDirection(Math.toDegrees(MathUtils.normalizeAngle2(leftEdge)),
range);
Point2D dest = calc.getDestinationGeographicPoint();
coords[1] = new Coordinate(dest.getX(), dest.getY());
// now the centre bearing
calc.setStartingGeographicPoint(new Point2D.Double(lon, lat));
calc.setDirection(Math.toDegrees(MathUtils.normalizeAngle2(bearing)),
range);
dest = calc.getDestinationGeographicPoint();
coords[2] = new Coordinate(dest.getX(), dest.getY());
// now the top-right
calc.setStartingGeographicPoint(new Point2D.Double(lon, lat));
calc.setDirection(Math.toDegrees(MathUtils.normalizeAngle2(rightEdge)),
range);
dest = calc.getDestinationGeographicPoint();
coords[3] = new Coordinate(dest.getX(), dest.getY());
// and back to the start
coords[4] = new Coordinate(coords[0]);
// ok, store the coordinates
CoordinateArraySequence seq = new CoordinateArraySequence(coords);
// and construct the bounded location object
LinearRing ls = new LinearRing(seq, factory);
Polygon poly = new Polygon(ls, null, factory);
LocationRange lr = new LocationRange(poly);
// do we have a bounds at this time?
BoundedState thisState = space.getBoundedStateAt(measurement.time);
if (thisState == null)
{
// ok, do the bounds
thisState = new BoundedState(measurement.time);
// and store it
space.add(thisState);
}
// ok, override any existing color for this state, if we have one
if (measurement.getColor() != null)
thisState.setColor(measurement.getColor());
// well, if we didn't - we do now! Apply it!
thisState.constrainTo(lr);
LineString bearingLine = GeoSupport.getFactory().createLineString(
new Coordinate[] { coords[0], coords[2] });
thisState.setBearingLine(bearingLine);
// also store the bearing value in the state - since it's of value in
// other processes (1959)
thisState.setBearingValue(bearing);
}
}
// hmm, do we run the MDA?
if (getAutoDetect())
{
// get a few bounded states
Collection<BoundedState> testStates = space.getBoundedStatesBetween(
this.getStartDate(), this.getFinishDate());
int ctr = 0;
for (Iterator<BoundedState> iterator = testStates.iterator(); iterator
.hasNext();)
{
BoundedState boundedState = iterator.next();
ctr++;
if (ctr >= 0 && ctr <= 3)
{
boundedState.setMemberOf("test MDA leg");
}
}
}
}
@Override
protected double cumulativeScoreFor(CoreRoute route)
{
double bearingError = this.bearingError == null ? 0 : this.bearingError;
if (!isActive() || route.getType() == LegType.ALTERING || bearingError == 0)
{
return 0;
}
double res = 0;
int count = 0;
for (BMeasurement measurement : measurements)
{
Date dateMeasurement = measurement.getDate();
if (dateMeasurement.compareTo(route.getStartTime()) >= 0
&& dateMeasurement.compareTo(route.getEndTime()) <= 0)
{
State state = route.getStateAt(dateMeasurement);
if (state != null && state.getLocation() != null)
{
GeodeticCalculator calculator = GeoSupport.createCalculator();
calculator.setStartingGeographicPoint(measurement.origin.getLon(),
measurement.origin.getLat());
calculator.setDestinationGeographicPoint(state.getLocation().getX(),
state.getLocation().getY());
double radians = MathUtils.normalizeAngle(Math.toRadians(calculator
.getAzimuth()));
double angleDiff = MathUtils.angleDiff(measurement.bearingAngle,
radians, true);
// make the error a proportion of the bearing error
angleDiff = angleDiff / (this.getBearingError());
// store the error
state.setScore(this, angleDiff * this.getWeight() / 10);
// and prepare the cumulative score
double thisError = angleDiff * angleDiff;
res += thisError;
count++;
}
}
}
if (count > 0)
{
res = Math.sqrt(res / count) / bearingError;
}
return res;
}
public void addMeasurement(double lat, double lon, Date date, double brg,
double range)
{
GeoPoint loc = new GeoPoint(lat, lon);
BMeasurement measure = new BMeasurement(loc, brg, date, range);
addMeasurement(measure);
}
public void loadFrom(List<String> lines)
{
// load from this source
// ;;IGNORE YYMMDD HHMMSS IGNORE IGNORE LAT_DEG LAT_MIN LAT_SEC LAT_HEM
// LONG_DEG LONG_MIN LONG_SEC LONG_HEM BEARING MAX_RNG
// ;SENSOR: 100112 121329 SENSOR @A 0 3 57.38 S 30 0 8.65 W 1.5 15000
// Read File Line By Line
for (String strLine : lines)
{
// hey, is this a comment line?
if (strLine.startsWith(";;"))
{
continue;
}
// ok, get parseing it
String[] elements = strLine.split("\\s+");
// now the date
String date = elements[1];
// and the time
String time = elements[2];
String latDegs = elements[5];
String latMins = elements[6];
String latSecs = elements[7];
String latHemi = elements[8];
String lonDegs = elements[9];
String lonMins = elements[10];
String lonSecs = elements[11];
String lonHemi = elements[12];
// and the beraing
String bearing = elements[13];
// and the range
String range = elements[14];
// ok,now construct the date=time
Date theDate = ObjectUtils.safeParseDate(new SimpleDateFormat(
"yyMMdd HHmmss"), date + " " + time);
// and the location
double lat = Double.valueOf(latDegs) + Double.valueOf(latMins) / 60d
+ Double.valueOf(latSecs) / 60d / 60d;
if (latHemi.toUpperCase().equals("S"))
lat = -lat;
double lon = Double.valueOf(lonDegs) + Double.valueOf(lonMins) / 60d
+ Double.valueOf(lonSecs) / 60d / 60d;
if (lonHemi.toUpperCase().equals("W"))
lon = -lon;
GeoPoint theLoc = new GeoPoint(lat, lon);
double angle = Math.toRadians(Double.parseDouble(bearing));
BMeasurement measure = new BMeasurement(theLoc, angle, theDate,
Double.parseDouble(range));
addMeasurement(measure);
}
this.setBearingError(Math.toRadians(3d));
}
/**
* get the bearing error
*
* @param errorRads
* (in radians)
*/
public Double getBearingError()
{
return bearingError;
}
public List<HostState> getHostState()
{
return states;
}
/**
* provide the bearing error
*
* @return (in radians)
*/
public void setBearingError(Double errorRads)
{
// IDIOT CHECK - CHECK WE HAVEN'T ACCIDENTALLY GOT DEGREES
if (errorRads > 2)
SATC_Activator.log(Status.WARNING,
"Looks like error is being presented in Degs", null);
Double old = bearingError;
this.bearingError = errorRads;
firePropertyChange(BEARING_ERROR, old, errorRads);
fireHardConstraintsChange();
}
public void setAutoDetect(boolean onAuto)
{
boolean previous = runMDA;
runMDA = onAuto;
firePropertyChange(RUN_MDA, previous, onAuto);
firePropertyChange(HARD_CONSTRAINTS, previous, onAuto);
}
public boolean getAutoDetect()
{
return runMDA;
}
/**
* utility class for storing a measurement
*
* @author ian
*
*/
public static class BMeasurement extends
CoreMeasurementContribution.CoreMeasurement
{
private static final double MAX_RANGE_METERS = 50000.;
private final GeoPoint origin;
private final double bearingAngle;
/**
* the (optional) maximum range for this measurement
*
*/
private final double range;
public BMeasurement(GeoPoint loc, double bearing, Date time, Double range)
{
super(time);
this.origin = loc;
this.bearingAngle = MathUtils.normalizeAngle(bearing);
// tidying up. Give the maximum possible range for this bearing if the
// data is missing
this.range = range == null ? MAX_RANGE_METERS : range;
}
}
public long[] getTimes(ArrayList<HostState> states)
{
long[] res = new long[states.size()];
int ctr = 0;
Iterator<HostState> iter = states.iterator();
while (iter.hasNext())
{
BearingMeasurementContribution.HostState hostState = (BearingMeasurementContribution.HostState) iter
.next();
res[ctr++] = hostState.time;
}
return res;
}
public double[] getCourses(ArrayList<HostState> states)
{
double[] res = new double[states.size()];
Iterator<HostState> iter = states.iterator();
int ctr = 0;
while (iter.hasNext())
{
BearingMeasurementContribution.HostState hostState = (BearingMeasurementContribution.HostState) iter
.next();
res[ctr++] = hostState.courseDegs;
}
return res;
}
public double[] getSpeeds(ArrayList<HostState> states)
{
double[] res = new double[states.size()];
Iterator<HostState> iter = states.iterator();
int ctr = 0;
while (iter.hasNext())
{
BearingMeasurementContribution.HostState hostState = (BearingMeasurementContribution.HostState) iter
.next();
res[ctr++] = hostState.speedKts;
}
return res;
}
public static class HostState
{
final public long time;
final public double courseDegs;
final public double speedKts;
public HostState(long time, double courseDegs, double speedKts)
{
this.time = time;
this.courseDegs = courseDegs;
this.speedKts = speedKts;
}
}
public void runMDA(final IContributions contributions)
{
// ok, we've got to find the ownship data, somehow :-(
if ((states == null) || (states.size() == 0))
{
return;
}
// ok, extract the ownship legs from this data
OwnshipLegDetector osLegDet = new OwnshipLegDetector();
List<LegOfData> ownshipLegs = osLegDet.identifyOwnshipLegs(getTimes(states),
getCourses(states), getSpeeds(states), 5);
// create object that can store the new legs
MyLegStorer storer = new MyLegStorer(contributions);
// ok, now collate the bearing data
ZigDetector detector = new ZigDetector();
// ok, work through the legs. In the absence of a Discrete
// Optimisation algorithm we're taking a brue force approach.
// Hopefully we can find an optimised alternative to this.
for (final Iterator<LegOfData> iterator2 = ownshipLegs.iterator(); iterator2
.hasNext();)
{
final LegOfData thisLeg = iterator2.next();
// ok, slice the data for this leg
long legStart = thisLeg.getStart();
long legEnd = thisLeg.getEnd();
// trim the start/end to the sensor data
legStart = Math.max(legStart, getStartDate().getTime());
legEnd = Math
.min(legEnd, getFinishDate().getTime());
List<Long> thisLegTimes = new ArrayList<Long>();
List<Double> thisLegBearings = new ArrayList<Double>();
ArrayList<BMeasurement> meas = getMeasurements();
Iterator<BMeasurement> iter = meas.iterator();
while (iter.hasNext())
{
BearingMeasurementContribution.BMeasurement measurement = (BearingMeasurementContribution.BMeasurement) iter
.next();
long thisTime = measurement.getDate().getTime();
if((thisTime >= legStart) && (thisTime <= legEnd))
{
thisLegTimes.add(measurement.getDate().getTime());
thisLegBearings.add(Math.toDegrees(measurement.bearingAngle));
}
}
detector.sliceThis("some name",legStart, legEnd, null, storer,
0.6, 0.000001, thisLegTimes, thisLegBearings);
}
// ok, slicing done!
if(_listeners != null)
{
Iterator<MDAResultsListener> iter = _listeners.iterator();
while (iter.hasNext())
{
BearingMeasurementContribution.MDAResultsListener thisL = (BearingMeasurementContribution.MDAResultsListener) iter
.next();
thisL.sliced(getName(), ownshipLegs, storer.getSlices(), states);
}
}
}
public void addSliceListener(MDAResultsListener listener)
{
if(_listeners == null)
_listeners = new ArrayList<MDAResultsListener>();
_listeners.add(listener);
}
public void removeSliceListener(MDAResultsListener listener)
{
if(_listeners != null)
_listeners.remove(listener);
}
private static class MyLegStorer implements ILegStorer
{
int ctr = 1;
private ArrayList<StraightLegForecastContribution> slices = new
ArrayList<StraightLegForecastContribution>();
private final IContributions _contributions;
public MyLegStorer(final IContributions theConts)
{
_contributions = theConts;
}
public ArrayList<StraightLegForecastContribution> getSlices()
{
return slices;
}
@Override
public void storeLeg(String scenarioName, long tStart, long tEnd,
Sensor sensor, double rms)
{
String name = "Leg-" + ctr++;
SATC_Activator.log(Status.INFO, " FOUND LEG FROM " + new Date(tStart) + " - " + new Date(tEnd), null);
StraightLegForecastContribution slf = new StraightLegForecastContribution();
slf.setStartDate(new Date(tStart));
slf.setFinishDate(new Date(tEnd));
slf.setActive(true);
slf.setName(name);
_contributions.addContribution(slf);
slices .add(slf);
}
}
public void addState(final HostState newState)
{
// check we have our states
if (states == null)
states = new ArrayList<HostState>();
// and store this new one
states.add(newState);
}
}
|
package org.devgateway.toolkit.persistence.mongo.spring;
import org.apache.commons.io.IOUtils;
import org.devgateway.ocds.persistence.mongo.DefaultLocation;
import org.devgateway.ocds.persistence.mongo.Organization;
import org.devgateway.ocds.persistence.mongo.Release;
import org.devgateway.ocds.persistence.mongo.flags.FlagsConstants;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.ScriptOperations;
import org.springframework.data.mongodb.core.index.Index;
import org.springframework.data.mongodb.core.index.TextIndexDefinition.TextIndexDefinitionBuilder;
import org.springframework.data.mongodb.core.script.ExecutableMongoScript;
import org.springframework.data.mongodb.core.script.NamedMongoScript;
import javax.annotation.PostConstruct;
import java.io.IOException;
import java.net.URL;
@Configuration
public class MongoTemplateConfiguration {
private final Logger logger = LoggerFactory.getLogger(MongoTemplateConfiguration.class);
@Autowired
private MongoTemplate mongoTemplate;
public void createMandatoryImportIndexes() {
//mongoTemplate.indexOps(Release.class).ensureIndex(new Index().on("planning.budget.projectID", Direction.ASC));
//mongoTemplate.indexOps(Location.class).ensureIndex(new Index().on("description", Direction.ASC));
mongoTemplate.indexOps(Organization.class).ensureIndex(new Index().on("identifier._id", Direction.ASC));
mongoTemplate.indexOps(Organization.class)
.ensureIndex(new Index().on("additionalIdentifiers._id", Direction.ASC));
mongoTemplate.indexOps(Organization.class).ensureIndex(
new Index().on("roles", Direction.ASC));
mongoTemplate.indexOps(Organization.class).ensureIndex(new Index().on("name", Direction.ASC).unique());
mongoTemplate.indexOps(DefaultLocation.class).ensureIndex(new Index().on("description", Direction.ASC));
logger.info("Added mandatory Mongo indexes");
}
public void createCorruptionFlagsIndexes() {
mongoTemplate.indexOps(Release.class).ensureIndex(new Index().on("flags.flaggedStats", Direction.ASC));
mongoTemplate.indexOps(Release.class).ensureIndex(new Index().on("flags.eligibleStats", Direction.ASC));
mongoTemplate.indexOps(Release.class).ensureIndex(new Index().on(FlagsConstants.I038_VALUE, Direction.ASC));
mongoTemplate.indexOps(Release.class).ensureIndex(new Index().on(FlagsConstants.I007_VALUE, Direction.ASC));
mongoTemplate.indexOps(Release.class).ensureIndex(new Index().on(FlagsConstants.I004_VALUE, Direction.ASC));
mongoTemplate.indexOps(Release.class).ensureIndex(new Index().on(FlagsConstants.I077_VALUE, Direction.ASC));
mongoTemplate.indexOps(Release.class).ensureIndex(new Index().on(FlagsConstants.I019_VALUE, Direction.ASC));
}
@PostConstruct
public void mongoPostInit() {
createMandatoryImportIndexes();
createPostImportStructures();
}
public void createPostImportStructures() {
createCorruptionFlagsIndexes();
// initialize some extra indexes
mongoTemplate.indexOps(Release.class).ensureIndex(new Index().on("ocid", Direction.ASC));
mongoTemplate.indexOps(Release.class).ensureIndex(new Index().on("tender.procurementMethod", Direction.ASC));
mongoTemplate.indexOps(Release.class)
.ensureIndex(new Index().on("tender.procurementMethodRationale", Direction.ASC));
mongoTemplate.indexOps(Release.class).ensureIndex(new Index().on("tender.status", Direction.ASC));
mongoTemplate.indexOps(Release.class).ensureIndex(new Index().on("awards.status", Direction.ASC));
mongoTemplate.indexOps(Release.class).ensureIndex(new Index().on("awards.suppliers._id", Direction.ASC));
mongoTemplate.indexOps(Release.class).ensureIndex(new Index().on("awards.date", Direction.ASC));
mongoTemplate.indexOps(Release.class).ensureIndex(new Index().on("awards.value.amount", Direction.ASC));
mongoTemplate.indexOps(Release.class).ensureIndex(new Index().on("tender.value.amount", Direction.ASC));
mongoTemplate.indexOps(Release.class).ensureIndex(new Index().on("tender.numberOfTenderers", Direction.ASC));
mongoTemplate.indexOps(Release.class).ensureIndex(new Index().on("tender.submissionMethod", Direction.ASC));
mongoTemplate.indexOps(Release.class)
.ensureIndex(new Index().on("tender.tenderPeriod.startDate", Direction.ASC));
mongoTemplate.indexOps(Release.class).ensureIndex(new Index().on("tender.tenderPeriod.endDate", Direction.ASC));
mongoTemplate.indexOps(Release.class)
.ensureIndex(new Index().on("tender.items.classification._id", Direction.ASC));
mongoTemplate.indexOps(Release.class).ensureIndex(new Index().
on("tender.items.deliveryLocation._id", Direction.ASC));
mongoTemplate.indexOps(Release.class).ensureIndex(new Index().
on("tender.items.deliveryLocation.geometry.coordinates", Direction.ASC));
mongoTemplate.indexOps(Organization.class).ensureIndex(new TextIndexDefinitionBuilder().onField("name")
.onField("id").onField("additionalIdentifiers._id").build());
logger.info("Added extra Mongo indexes");
ScriptOperations scriptOps = mongoTemplate.scriptOps();
// add script to calculate the percentiles endpoint
URL scriptFile = getClass().getResource("/tenderBidPeriodPercentilesMongo.js");
try {
String scriptText = IOUtils.toString(scriptFile);
ExecutableMongoScript script = new ExecutableMongoScript(scriptText);
scriptOps.register(new NamedMongoScript("tenderBidPeriodPercentiles", script));
} catch (IOException e) {
e.printStackTrace();
}
// add general mongo system helper methods
URL systemScriptFile = getClass().getResource("/mongoSystemScripts.js");
try {
String systemScriptFileText = IOUtils.toString(systemScriptFile);
ExecutableMongoScript script = new ExecutableMongoScript(systemScriptFileText);
scriptOps.execute(script);
} catch (IOException e) {
e.printStackTrace();
}
}
}
|
package eu.cloudscaleproject.env.toolchain.util;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.BusyIndicator;
import org.eclipse.swt.custom.StackLayout;
import org.eclipse.swt.events.DisposeEvent;
import org.eclipse.swt.events.DisposeListener;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.layout.FormAttachment;
import org.eclipse.swt.layout.FormData;
import org.eclipse.swt.layout.FormLayout;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Layout;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.views.properties.IPropertySheetPage;
import eu.cloudscaleproject.env.common.ColorResources;
import eu.cloudscaleproject.env.common.interfaces.IRefreshable;
import eu.cloudscaleproject.env.common.interfaces.ISelectable;
import eu.cloudscaleproject.env.common.ui.GradientComposite;
import eu.cloudscaleproject.env.common.ui.HoverButton;
import eu.cloudscaleproject.env.common.ui.HoverToggleButton;
import eu.cloudscaleproject.env.common.ui.util.ColorHelper;
import eu.cloudscaleproject.env.toolchain.IDirtyAdapter;
import eu.cloudscaleproject.env.toolchain.IPropertySheetPageProvider;
import eu.cloudscaleproject.env.toolchain.ProjectEditorSelectionService;
import eu.cloudscaleproject.env.toolchain.resources.types.IEditorInput;
import eu.cloudscaleproject.env.toolchain.resources.types.IEditorInputResource;
public abstract class AbstractSidebarEditor implements ISidebarEditor{
//private static final Logger logger = Logger.getLogger(AbstractSidebarEditor.class.getName());
private StackLayout stackLayout;
private final Composite compositeSidebar;
private final Composite compositeArea;
private Composite emptyPanel;
private Composite compositeSidebarList = null;
private Composite compositeSidebarControls = null;
private boolean btnNewFromEnabled = true;
private boolean btnNewEnabled = true;
private boolean btnRemoveEnabled = true;
protected final LinkedHashMap<IEditorInput, EditorItem> entries
= new LinkedHashMap<IEditorInput, EditorItem>();
// user-implemented methods ////////////
public abstract Composite createInputComposite(IEditorInput input, Composite parent, int style);
public void handleNewInput(IEditorInput selected){};
public void handleNewInputFrom(IEditorInput selected){};
public void handleInputDelete(IEditorInput toDelete){};
public void handleSelect(IEditorInput selected){};
public class EditorItem implements IPropertySheetPageProvider{
private final IEditorInput input;
private final String sectionName;
private HoverToggleButton btnSelect;
private Composite composite;
private Color color_select;
private Color color_hover;
public boolean isSelected = false;
final PropertyChangeListener eirChangeListener = new PropertyChangeListener() {
@Override
public void propertyChange(final PropertyChangeEvent evt) {
Display.getDefault().syncExec(new Runnable() {
public void run() {
resourceChanged(evt);
};
});
// When non GUI thread => WorkbenchWidow == null
if (Display.getDefault().getThread() != Thread.currentThread()) return;
IEditorPart editor = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage().getActiveEditor();
if(editor != null){
IDirtyAdapter dirtyAdapter = (IDirtyAdapter)editor.getAdapter(IDirtyAdapter.class);
if(dirtyAdapter != null){
dirtyAdapter.fireDirtyState();
}
}
}
};
public EditorItem(IEditorInput input, String sectionName, int style) {
this.input = input;
this.sectionName = sectionName;
initialize();
this.input.addPropertyChangeListener(eirChangeListener);
EditorRegistry.getInstance().registerEditorItem(AbstractSidebarEditor.this, EditorItem.this);
}
public void resourceChanged(PropertyChangeEvent evt){
if(composite == null || composite.isDisposed()){
return;
}
if(btnSelect == null || btnSelect.isDisposed()){
return;
}
if (IEditorInputResource.PROP_LOADED.equals(evt.getPropertyName()))
{
btnSelect.setText(input.getName());
btnSelect.redraw();
if(composite instanceof IRefreshable){
((IRefreshable)composite).refresh();
}
}
if(IEditorInputResource.PROP_NAME.equals(evt.getPropertyName())){
btnSelect.setText((String)evt.getNewValue());
btnSelect.redraw();
}
}
public IEditorInput getInput()
{
return input;
}
public Composite getComposite()
{
return composite;
}
private List<ISaveable> getSaveables(){
List<ISaveable> out = new ArrayList<>();
collectSaveableComposites(out, composite);
return out;
}
public boolean isDirty(){
if(this.input instanceof IEditorInputResource){
IEditorInputResource res = (IEditorInputResource)input;
return res.isDirty();
}
for(ISaveable s : getSaveables()){
if(s.isDirty()){
return true;
}
}
return false;
}
private void collectSaveableComposites(List<ISaveable> composites, Composite c){
if(c == null || c.isDisposed()){
return;
}
if(c instanceof ISaveable){
composites.add((ISaveable)c);
return;
}
for(Control control : c.getChildren()){
if(control instanceof Composite){
collectSaveableComposites(composites, (Composite)control);
}
}
}
public void save(){
BusyIndicator.showWhile(Display.getDefault(), new Runnable() {
@Override
public void run() {
if(input instanceof IEditorInputResource){
IEditorInputResource res = (IEditorInputResource)input;
if(res.isDirty()){
res.save();
}
}
for(ISaveable s : getSaveables()){
if(s.isDirty()){
s.save();
}
}
}
});
}
public void load(final boolean force){
BusyIndicator.showWhile(Display.getDefault(), new Runnable() {
@Override
public void run() {
if(input instanceof IEditorInputResource){
if(composite != null && !composite.isDisposed()){
composite.dispose();
}
IEditorInputResource res = (IEditorInputResource)input;
synchronized (res) {
if(!res.isLoaded() || force){
res.load();
}
}
/*
if(isSelected){
select();
}
*/
}
}
});
}
private void initialize(){
BusyIndicator.showWhile(Display.getDefault(), new Runnable() {
@Override
public void run() {
load(false);
}
});
initButton();
}
private void checkWidgets(){
initButton();
initComposite();
}
private void initButton(){
if(btnSelect == null || btnSelect.isDisposed()){
btnSelect = new HoverToggleButton(compositeSidebarList, SWT.NONE);
Control c = getLastControlInSidebar(sectionName);
if(c != null){
btnSelect.moveBelow(c);
}
btnSelect.setAlignmentHorizontal(SWT.LEFT);
btnSelect.setIndentHorizontal(10);
GridData gd_btnSelect = new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1);
btnSelect.setLayoutData(gd_btnSelect);
btnSelect.setText(input.getName());
//style
if(color_select == null || color_select.isDisposed()){
color_select = ColorHelper.deviateSaturation(getSidebarBackgroundColor(), 0.1);
}
if(color_hover == null || color_hover.isDisposed()){
color_hover = ColorHelper.deviateValue(color_select, 0.1);
}
btnSelect.setBackground(getSidebarBackgroundColor());
btnSelect.setBackgroundSelected(color_select);
btnSelect.setBackgroundHover(color_hover);
btnSelect.setForeground(getSidebarForegroundColor());
btnSelect.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
select();
}
});
btnSelect.addDisposeListener(new DisposeListener() {
@Override
public void widgetDisposed(DisposeEvent e) {
EditorItem.this.dispose();
}
});
}
}
private void initComposite(){
if(composite == null || composite.isDisposed()){
composite = createInputComposite(input, compositeArea, SWT.NONE);
}
}
public void update() {
checkWidgets();
if(composite instanceof IRefreshable){
((IRefreshable)composite).refresh();
}
btnSelect.setText(this.input.getName());
btnSelect.update();
}
public void select(){
checkWidgets();
for(EditorItem ei : entries.values()){
ei.initButton();
ei.btnSelect.setSelection(false);
ei.isSelected = false;
}
btnSelect.setSelection(true);
stackLayout.topControl = composite;
isSelected = true;
update();
handleSelect(input);
compositeArea.layout();
composite.setFocus();
ProjectEditorSelectionService.getInstance().reloadPropertySheetPage();
if(composite instanceof ISelectable){
((ISelectable)composite).onSelect();
}
}
public void dispose() {
input.removePropertyChangeListener(eirChangeListener);
if(btnSelect != null){
btnSelect.dispose();
}
if(composite != null){
composite.dispose();
}
if(color_hover != null){
color_hover.dispose();
}
if(color_select != null){
color_select.dispose();
}
}
@Override
public IPropertySheetPage getPropertySheetPage() {
if(composite instanceof IPropertySheetPageProvider){
IPropertySheetPageProvider propProvider = (IPropertySheetPageProvider)composite;
return propProvider.getPropertySheetPage();
}
return null;
}
}
public AbstractSidebarEditor(Composite sidebar, Composite area) {
this.compositeSidebar = sidebar;
this.compositeArea = area;
EditorRegistry.getInstance().registerEditor(this);
}
public Map<IEditorInput, EditorItem> getEntries()
{
return entries;
}
public void init(){
//dispose composites first
dispose();
//rebuild side-bar items and area composites
GridLayout gl_compositSidebar = new GridLayout(1, false);
gl_compositSidebar.marginTop = 0;
gl_compositSidebar.marginHeight = 0;
gl_compositSidebar.marginWidth = 0;
gl_compositSidebar.verticalSpacing = 0;
compositeSidebar.setLayout(gl_compositSidebar);
//composite that holds side-bar hover buttons
compositeSidebarList = new GradientComposite(compositeSidebar, SWT.NONE);
compositeSidebarList.setBackground(getSidebarBackgroundColor());
compositeSidebarList.setBounds(10, 10, 129, 280);
GridLayout gl_compositSidebarList = new GridLayout(1, false);
gl_compositSidebarList.marginTop = 0;
gl_compositSidebarList.marginHeight = 0;
gl_compositSidebarList.marginWidth = 1;
gl_compositSidebarList.verticalSpacing = 1;
compositeSidebarList.setLayout(gl_compositSidebarList);
GridData gd_compositeSidebarList = new GridData(SWT.FILL, SWT.FILL, false, true, 1, 1);
gd_compositeSidebarList.widthHint = 160;
gd_compositeSidebarList.minimumWidth = 120;
compositeSidebarList.setLayoutData(gd_compositeSidebarList);
//create or retrieve stack layout of the area composite
Layout areaLayout = compositeArea.getLayout();
if(areaLayout == null || !(areaLayout instanceof StackLayout)){
stackLayout = new StackLayout();
stackLayout.marginHeight = 0;
compositeArea.setLayout(stackLayout);
}
else{
stackLayout = (StackLayout)areaLayout;
}
//create empty panel
emptyPanel = createEmptyPanel(compositeArea);
//create hover buttons and area composites from IEditorInput objects
String[] sections = getSidebarSections();
if(sections != null){
for(String section : sections){
createSidebarSection(section, SWT.NONE);
}
}
else{
createSidebarSection(null, SWT.NONE);
}
//select the first item or show the empty panel
{
Iterator<EditorItem> iter = entries.values().iterator();
if(iter.hasNext()){
iter.next().select();
}
else{
stackLayout.topControl = emptyPanel;
}
}
//rebuild controls composite
initControls();
//layout recreated composites
if(compositeSidebar != null && !compositeSidebar.isDisposed()){
compositeSidebar.layout();
}
if(compositeArea != null && !compositeArea.isDisposed()){
compositeArea.layout();
}
}
private void initControls(){
if(compositeSidebarList == null || compositeSidebarList.isDisposed()){
return;
}
if(compositeSidebarControls != null){
compositeSidebarControls.dispose();
}
compositeSidebarControls = new GradientComposite(compositeSidebar, SWT.NONE);
compositeSidebarControls.setBackground(getSidebarBackgroundColor());
GridLayout gl_compositeControls = new GridLayout(1, false);
gl_compositeControls.horizontalSpacing = 0;
gl_compositeControls.verticalSpacing = 1;
gl_compositeControls.marginWidth = 1;
gl_compositeControls.marginHeight = 1;
compositeSidebarControls.setLayout(gl_compositeControls);
GridData gd_compositeControls = new GridData(SWT.FILL, SWT.FILL, false, false, 1, 1);
gd_compositeControls.widthHint = 96;
compositeSidebarControls.setLayoutData(gd_compositeControls);
if(btnNewEnabled){
HoverButton btnNew = new HoverButton(compositeSidebarControls, SWT.NONE);
btnNew.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false, 1, 1));
btnNew.setText("Create");
btnNew.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
EditorItem selected = getCurrentSelectionItem();
if(selected != null){
handleNewInput(selected.input);
}
else{
handleNewInput(null);
}
}
});
}
if(btnNewFromEnabled){
HoverButton btnNewFromSelection = new HoverButton(compositeSidebarControls, SWT.NONE);
btnNewFromSelection.setLayoutData(new GridData(SWT.FILL, SWT.FILL, false, false, 2, 1));
btnNewFromSelection.setText("Clone");
btnNewFromSelection.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
EditorItem selected = getCurrentSelectionItem();
if(selected != null){
handleNewInputFrom(selected.input);
}
}
});
}
if(btnRemoveEnabled){
HoverButton btnRemove = new HoverButton(compositeSidebarControls, SWT.NONE);
btnRemove.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false, 1, 1));
btnRemove.setText("Delete");
btnRemove.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
EditorItem selected = getCurrentSelectionItem();
if(selected != null){
handleInputDelete(selected.input);
}
}
});
}
}
private Composite createEmptyPanel(Composite parent){
Composite c = new Composite(parent, SWT.NONE);
FormLayout layout= new FormLayout();
layout.marginHeight = 5;
layout.marginWidth = 5;
c.setLayout(layout);
Label label = new Label(c, SWT.NONE);
label.setText("Currently there are no entries to display. Create new one?");
FormData lb_formData = new FormData();
lb_formData.top = new FormAttachment(0,30);
lb_formData.left = new FormAttachment(15,0);
label.setLayoutData(lb_formData);
Button button = new Button(c, SWT.NONE);
button.setText("Create new...");
button.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
handleNewInput(null);
}
});
FormData b_formData = new FormData();
b_formData.top = new FormAttachment(label, 5);
b_formData.left = new FormAttachment(15,0);
button.setLayoutData(b_formData);
return c;
}
public EditorItem getCurrentSelectionItem(){
for(EditorItem ei : entries.values()){
if(ei.isSelected){
return ei;
}
}
return null;
}
public int getCurrentSelectionIndex(){
int i = 0;
for(EditorItem ei : entries.values()){
if(ei.isSelected){
return i;
}
i++;
}
return -1;
}
public void setCurrentSelectionIndex(int index){
int i = 0;
for(EditorItem ei : entries.values()){
if(i == index){
ei.select();
return;
}
i++;
}
}
public Composite getCurrentSelection(){
EditorItem ei = getCurrentSelectionItem();
if(ei != null){
return ei.composite;
}
return null;
}
@Override
public void setNewButtonEnabled(boolean enable){
this.btnNewEnabled = enable;
initControls();
}
@Override
public void setNewFromButtonEnabled(boolean enabled){
this.btnNewFromEnabled = enabled;
initControls();
}
@Override
public void setRemoveButtonEnabled(boolean enabled){
this.btnRemoveEnabled = enabled;
initControls();
}
public void showInput(IEditorInput input){
EditorItem epc = entries.get(input);
if(epc == null){
return;
}
epc.select();
}
public void addSidebarEditor(IEditorInput ei, String section){
// Workaround - entry can already exist - thread fuck
if (entries.get(ei) != null) return;
EditorItem newEditorItem = new EditorItem(ei, section, SWT.NONE);
entries.put(ei, newEditorItem);
compositeArea.redraw();
compositeArea.layout(true);
compositeSidebarList.redraw();
compositeSidebarList.layout(true);
newEditorItem.select();
}
public void removeSidebarEditor(IEditorInput editorInput){
//select another item
int selIndex = getCurrentSelectionIndex();
int newIndex = selIndex > 0 ? selIndex - 1 : selIndex;
EditorItem editorItem = entries.get(editorInput);
if(editorItem != null){
editorItem.dispose();
}
else{
//editor item already removed
return;
}
entries.remove(editorInput);
compositeArea.layout(true);
compositeSidebarList.layout(true);
if(newIndex < entries.size()){
setCurrentSelectionIndex(newIndex);
}
else{
stackLayout.topControl = emptyPanel;
compositeArea.layout();
}
}
public void save(){
for(EditorItem ei : entries.values()){
ei.save();
}
}
public void load(boolean force){
EditorItem ei = getCurrentSelectionItem();
if(ei != null){
ei.load(force);
}
}
public boolean isDirty(){
for(EditorItem ei : entries.values()){
if(ei.isDirty()){
return true;
}
}
return false;
}
public void update(){
//update selection
EditorItem selectedItem = getCurrentSelectionItem();
if(selectedItem != null){
selectedItem.update();
}
compositeArea.update();
compositeSidebar.update();
}
public Color getSidebarSectionBackgroundColor(){
return ColorResources.COLOR_CS_BLUE;
}
public Color getSidebarSectionForegroundColor(){
return ColorResources.COLOR_BLACK;
}
public Color getSidebarBackgroundColor(){
return ColorResources.COLOR_CS_BLUE_LIGHT;
}
public Color getSidebarForegroundColor(){
return ColorResources.COLOR_CS_BLUE_DARK;
}
private Control getLastControlInSidebar(String section){
Control out = null;
boolean inSection = false;
for(Control c : compositeSidebarList.getChildren()){
if(c instanceof Label){
Label l = (Label)c;
if(l.getText().equals(section)){
inSection = true;
}
else{
inSection = false;
}
}
if(inSection){
out = c;
}
}
return out;
}
private void createSidebarSection(String sectionName, int style){
//generate section label
if(sectionName != null){
final GradientComposite c = new GradientComposite(compositeSidebarList, SWT.NONE);
c.setGradientDirection(false);
c.setGradientColorStart(getSidebarSectionBackgroundColor());
c.setGradientColorEnd(getSidebarBackgroundColor());
c.setLayout(new GridLayout(1, false));
GridData gd_c = new GridData(SWT.FILL, SWT.FILL, true, false);
gd_c.heightHint = 25;
c.setLayoutData(gd_c);
Label label = new Label(c, SWT.NONE);
label.setForeground(getSidebarSectionForegroundColor());
label.setText(sectionName);
label.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false));
}
//generate section entries
List<IEditorInput> inputs = getInputs(sectionName);
if(inputs != null){
for(IEditorInput input : inputs){
entries.put(input, new EditorItem(input, sectionName, style));
}
}
}
@Override
public IPropertySheetPage getPropertySheetPage() {
EditorItem ei = getCurrentSelectionItem();
if(ei != null){
return ei.getPropertySheetPage();
}
return null;
}
public void dispose() {
for(EditorItem item : entries.values()){
item.dispose();
}
entries.clear();
if(compositeSidebarList != null && !compositeSidebarList.isDisposed()){
compositeSidebarList.dispose();
}
if(compositeSidebarControls != null && !compositeSidebarControls.isDisposed()){
compositeSidebarControls.dispose();
}
}
}
|
package org.opencps.paymentmgt.service.impl;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import org.opencps.paymentmgt.model.PaymentFile;
import org.opencps.paymentmgt.service.base.PaymentFileLocalServiceBaseImpl;
import com.liferay.portal.kernel.log.Log;
import com.liferay.portal.kernel.log.LogFactoryUtil;
import com.liferay.portal.kernel.exception.PortalException;
import com.liferay.portal.kernel.exception.SystemException;
import com.liferay.portal.kernel.repository.model.FileEntry;
import com.liferay.portal.kernel.util.OrderByComparator;
import com.liferay.portal.kernel.util.Validator;
import com.liferay.portal.model.User;
import com.liferay.portal.security.permission.PermissionChecker;
import com.liferay.portal.security.permission.PermissionCheckerFactoryUtil;
import com.liferay.portal.security.permission.PermissionThreadLocal;
import com.liferay.portal.service.ServiceContext;
import com.liferay.portal.service.UserLocalServiceUtil;
/**
* The implementation of the Payment file local service.
*
* <p>
* All custom service methods should be put in this class. Whenever methods are added, rerun ServiceBuilder to copy their definitions into the {@link org.opencps.paymentmgt.service.PaymentFileLocalService} interface.
*
* <p>
* This is a local service. Methods of this service will not have security checks based on the propagated JAAS credentials because this service can only be accessed from within the same VM.
* </p>
*
* @author trungdk
* @see org.opencps.paymentmgt.service.base.PaymentFileLocalServiceBaseImpl
* @see org.opencps.paymentmgt.service.PaymentFileLocalServiceUtil
*/
public class PaymentFileLocalServiceImpl extends PaymentFileLocalServiceBaseImpl {
/**
* @param keypayTransactionId
* @return
* @throws PortalException
* @throws SystemException
*/
public PaymentFile getByTransactionId(long keypayTransactionId)
throws PortalException, SystemException {
return paymentFilePersistence.fetchByT_I(keypayTransactionId);
}
/**
* @param keypayGoodCode
* @return
* @throws PortalException
* @throws SystemException
*/
public PaymentFile getByGoodCode(String keypayGoodCode)
throws PortalException, SystemException {
return paymentFilePersistence.fetchByG_C(keypayGoodCode);
}
/**
* @param dossierId
* @return
* @throws PortalException
* @throws SystemException
*/
public int countAllPaymentFile(long dossierId)
throws PortalException, SystemException {
return paymentFilePersistence.countByD_(dossierId);
}
/**
* @param dossierId
* @param paymentStatus
* @return
* @throws PortalException
* @throws SystemException
*/
public int countPaymentFile(long dossierId, int paymentStatus)
throws PortalException, SystemException {
return paymentFilePersistence.countByD_P(dossierId, paymentStatus);
}
/*
* NOTE FOR DEVELOPERS:
*
* Never reference this interface directly. Always use {@link org.opencps.paymentmgt.service.PaymentFileLocalServiceUtil} to access the Payment file local service.
*/
public PaymentFile addPaymentFile(
long userId, long dossierId, long fileGroupId, long ownerUserId,
long ownerOrganizationId, long govAgencyOrganizationId,
String paymentName, Date requestDatetime, Double amount,
String requestNote, String placeInfo, ServiceContext serviceContext)
throws SystemException {
long paymentFileId =
counterLocalService.increment(PaymentFile.class.getName());
PaymentFile paymentFile = paymentFilePersistence.create(paymentFileId);
Date now = new Date();
paymentFile.setUserId(userId);
paymentFile.setGroupId(serviceContext.getScopeGroupId());
paymentFile.setCompanyId(serviceContext.getCompanyId());
paymentFile.setCreateDate(now);
paymentFile.setModifiedDate(now);
// paymentFile
// .setUuid(PortalUUIDUtil
// .generate());
paymentFile.setDossierId(dossierId);
paymentFile.setFileGroupId(fileGroupId);
paymentFile.setOwnerUserId(ownerUserId);
paymentFile.setOwnerOrganizationId(ownerOrganizationId);
paymentFile.setPaymentName(paymentName);
paymentFile.setRequestDatetime(requestDatetime);
paymentFile.setAmount(amount);
paymentFile.setRequestNote(requestNote);
paymentFile.setPlaceInfo(placeInfo);
paymentFile.setPaymentStatus(0);
paymentFile.setGovAgencyOrganizationId(govAgencyOrganizationId);
// govAgencyOrganizationId > 0 insert
// paymentFile.setGovAgencyTaxNo(govAgencyTaxNo);
// paymentFile.setInvoiceTemplateNo(invoiceTemplateNo);
// paymentFile.setInvoiceIssueNo(invoiceIssueNo);
// paymentFile.setInvoiceNo(invoiceNo);
return paymentFilePersistence.update(paymentFile);
}
public List<PaymentFile> searchPaymentFiles(
long groupId, int paymentStatus, String keywords, int start, int end) {
List<PaymentFile> listPaymentFile = new ArrayList<PaymentFile>();
try {
listPaymentFile = paymentFileFinder.searchPaymentFiles(
groupId, paymentStatus, keywords, start, end);
} catch (SystemException e) {
// TODO Auto-generated catch block
_log.error(e);
}
return listPaymentFile;
}
public int countPaymentFiles(
long groupId, int paymentStatus, String keywords) {
try {
return paymentFileFinder.countPaymentFiles(
groupId, paymentStatus, keywords);
} catch (SystemException e) {
// TODO Auto-generated catch block
_log.error(e);
}
return 0;
}
public int countCustomerPaymentFile(
long groupId, String keyword, boolean isCitizen, long customerId,
int paymentStatus) {
return paymentFileFinder.countCustomerPaymentFile(
groupId, keyword, isCitizen, customerId, paymentStatus);
}
public List<PaymentFile> searchCustomerPaymentFile(
long groupId, String keyword, boolean isCitizen, long customerId,
int paymentStatus, int start, int end, OrderByComparator obc) {
return paymentFileFinder.searchCustomerPaymentFile(
groupId, keyword, isCitizen, customerId, paymentStatus, start, end,
obc);
}
public int countCustomerPaymentFileNewRequest(
long groupId, String keyword, boolean isCitizen, long customerId,
int[] paymentStatus) {
return paymentFileFinder.countCustomerPaymentFileNewRequest(
groupId, keyword, isCitizen, customerId, paymentStatus);
}
public List<PaymentFile> searchCustomerPaymentFileNewRequest(
long groupId, String keyword, boolean isCitizen, long customerId,
int[] paymentStatus, int start, int end, OrderByComparator obc) {
return paymentFileFinder.searchCustomerPaymentFileNewRequest(
groupId, keyword, isCitizen, customerId, paymentStatus, start, end,
obc);
}
public PaymentFile getPaymentFileByGoodCode(
long groupId, String keypayGoodCode)
throws SystemException {
return paymentFilePersistence.fetchByGoodCode(groupId, keypayGoodCode);
}
public PaymentFile getPaymentFileByMerchantResponse(
long keypayTransactionId, String keypayGoodCode, double amount)
throws SystemException {
return paymentFilePersistence.fetchByMerchantResponse(
keypayTransactionId, keypayGoodCode, amount);
}
/**
* @param dossierId
* @param fileGroupId
* @param ownerUserId
* @param ownerOrganizationId
* @param govAgencyOrganizationId
* @param paymentName
* @param requestDatetime
* @param amount
* @param requestNote
* @param placeInfo
* @return
* @throws SystemException
*/
public PaymentFile addPaymentFile(
long dossierId, long fileGroupId, long ownerUserId,
long ownerOrganizationId, long govAgencyOrganizationId,
String paymentName, Date requestDatetime, Double amount,
String requestNote, String placeInfo, String paymentOptions)
throws SystemException {
long paymentFileId =
counterLocalService.increment(PaymentFile.class.getName());
PaymentFile paymentFile = paymentFilePersistence.create(paymentFileId);
Date now = new Date();
paymentFile.setCreateDate(now);
paymentFile.setModifiedDate(now);
paymentFile.setDossierId(dossierId);
paymentFile.setFileGroupId(fileGroupId);
paymentFile.setOwnerUserId(ownerUserId);
paymentFile.setOwnerOrganizationId(ownerOrganizationId);
paymentFile.setPaymentName(paymentName);
paymentFile.setRequestDatetime(requestDatetime);
paymentFile.setAmount(amount);
paymentFile.setRequestNote(requestNote);
paymentFile.setPlaceInfo(placeInfo);
paymentFile.setPaymentStatus(0);
paymentFile.setPaymentOptions(paymentOptions);
paymentFile.setGovAgencyOrganizationId(govAgencyOrganizationId);
return paymentFilePersistence.update(paymentFile);
}
/**
* @param paymentFileId
* @param keypayUrl
* @param keypayTransactionId
* @param keypayGoodCode
* @param keypayMerchantCode
* @return
* @throws PortalException
* @throws SystemException
*/
public PaymentFile updatePaymentFile(
long paymentFileId, String keypayUrl, long keypayTransactionId,
String keypayGoodCode, String keypayMerchantCode)
throws PortalException, SystemException {
PaymentFile paymentFile =
paymentFilePersistence.fetchByPrimaryKey(paymentFileId);
paymentFile.setKeypayUrl(keypayUrl);
paymentFile.setKeypayTransactionId(keypayTransactionId);
paymentFile.setKeypayGoodCode(keypayGoodCode);
paymentFile.setKeypayMerchantCode(keypayMerchantCode);
paymentFilePersistence.update(paymentFile);
return paymentFile;
}
public List<PaymentFile> getPaymentFileByD_(long dossierId) throws SystemException {
return paymentFilePersistence.findByD_(dossierId);
}
public PaymentFile syncPaymentFile(
String oid, String typeUpdate, int paymentStatus, int paymentMethod,
String approveNote, byte[] bytes, long folderId, String sourceFileName,
String mimeType, String title, String description, String changeLog,
ServiceContext serviceContext)
throws PortalException, SystemException {
PaymentFile paymentFile = paymentFilePersistence.findByOID(oid);
paymentFile.setPaymentStatus(paymentStatus);
paymentFile.setPaymentMethod(paymentMethod);
if (Validator.isNotNull(approveNote)) {
paymentFile.setApproveNote(approveNote);
}
paymentFile.setApproveNote(approveNote);
User user = UserLocalServiceUtil.getUser(serviceContext.getUserId());
PermissionChecker permissionChecker;
try {
permissionChecker = PermissionCheckerFactoryUtil.create(user);
PermissionThreadLocal.setPermissionChecker(permissionChecker);
}
catch (Exception e) {
}
FileEntry fileEntry =
dlAppLocalService.addFileEntry(
serviceContext.getUserId(), serviceContext.getScopeGroupId(),
folderId, sourceFileName, mimeType, title, description,
changeLog, bytes, serviceContext);
paymentFile.setConfirmFileEntryId(fileEntry.getFileEntryId());
paymentFilePersistence.update(paymentFile);
return paymentFile;
}
private Log _log = LogFactoryUtil.getLog(PaymentFileLocalServiceImpl.class);
}
|
package org.jtalks.poulpe.web.controller.component;
import org.hibernate.validator.constraints.NotEmpty;
import org.jtalks.common.model.entity.Component;
import org.jtalks.common.model.entity.ComponentType;
import org.jtalks.common.validation.ValidationException;
import org.jtalks.poulpe.service.ComponentService;
import org.jtalks.poulpe.web.controller.DialogManager;
import org.jtalks.poulpe.web.controller.WindowManager;
import org.zkoss.bind.annotation.Command;
import org.zkoss.bind.annotation.NotifyChange;
import org.zkoss.util.resource.Labels;
import org.zkoss.zk.ui.Executions;
import javax.annotation.Nonnull;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* ViewModel class for EditComponent View
*
* @author Vahluev Vyacheslav
*/
public class EditCompViewModel {
public static final String EMPTY_TITLE = "component.error.title_shouldnt_be_empty";
public static final String EMPTY_NAME = "component.error.name_shouldnt_be_empty";
public static final String ITEM_ALREADY_EXISTS = "item.already.exist";
/**
* Current component we are working with
*/
private Component currentComponent = (Component) Executions.getCurrent().getDesktop()
.getAttribute("componentToEdit");
/**
* The name of the component
*/
private String name;
/**
* The description of the component
*/
private String description;
/**
* The name of the component
*/
private String componentName;
/**
* Type of the component
*/
private String componentType;
/**
* The caption of the forum
*/
private String caption;
/**
* The post preview size of the forum
*/
private String postPreviewSize;
private String sessionTimeout;
/**
* Web-form validation messages
*/
private Map<String, String> validationMessages = new HashMap<String, String>();
protected ComponentService componentService;
protected DialogManager dialogManager;
protected WindowManager windowManager;
/**
* Sets the service instance which is used for manipulating with stored
* components.
*
* @param componentService
* the new value of the service instance
*/
public void setComponentService(ComponentService componentService) {
this.componentService = componentService;
}
/**
* Sets the dialog manager which is used for showing different types of
* dialog messages.
*
* @param dialogManager
* the new value of the dialog manager
*/
public void setDialogManager(DialogManager dialogManager) {
this.dialogManager = dialogManager;
}
/**
* Sets window manager.
*
* @param windowManager
* the new window manager
*/
public void setWindowManager(WindowManager windowManager) {
this.windowManager = windowManager;
}
// constructor
/**
* Default constructor. Inits the data on the form.
*
* @param componentService
* service we use to access components
*/
public EditCompViewModel(@Nonnull ComponentService componentService) {
this.setComponentService(componentService);
initData();
}
/**
* Inits the data on the form.
*/
@NotifyChange({ "componentName", "name", "description", "caption", "postPreviewSize", "sessionTimeout" })
public void initData() {
currentComponent = (Component) Executions.getCurrent().getDesktop().getAttribute("componentToEdit");
if (currentComponent.getComponentType().equals(ComponentType.FORUM)) {
componentType = "jcommune";
} else {
componentType = "antarcticle";
}
componentName = valueOf(currentComponent.getName());
name = valueOf(currentComponent.getProperty(componentType + ".name"));
description = valueOf(currentComponent.getDescription());
caption = valueOf(currentComponent.getProperty(componentType + ".caption"));
postPreviewSize = valueOf(currentComponent.getProperty(componentType + ".postPreviewSize"));
sessionTimeout = valueOf(currentComponent.getProperty(componentType + ".session_timeout"));
}
// service functions
/**
* Returns all components.
*
* @return the list of the components
*/
public List<Component> getComponents() {
return componentService.getAll();
}
// commands
/**
* Saves a component. Shows validation messages, if something is wrong
*/
@Command()
@NotifyChange({ "componentName", "name", "description", "caption", "postPreviewSize", "sessionTimeout" })
public void save() {
boolean correct = true;
validationMessages.clear();
if (checkCorrect()) {
currentComponent.setName(componentName);
currentComponent.setDescription(description);
currentComponent.setProperty(componentType + ".name", name);
currentComponent.setProperty(componentType + ".caption", caption);
currentComponent.setProperty(componentType + ".postPreviewSize", postPreviewSize);
currentComponent.setProperty(componentType + ".session_timeout", sessionTimeout);
try {
componentService.saveComponent(currentComponent);
} catch (ValidationException e) {
validationMessages.put("componentName", Labels.getLabel(ITEM_ALREADY_EXISTS));
correct = false;
}
if (correct) {
validationMessages.clear();
Executions.sendRedirect("");
}
}
}
/**
* Cancels all the actions
*/
@Command()
@NotifyChange({ "componentName", "name", "description", "caption", "postPreviewSize", "validationMessages",
"sessionTimeout" })
public void cancel() {
initData();
validationMessages.clear();
Executions.sendRedirect("");
}
// helpers
/**
* Returns string value of the field or empty string if string is null
*
* @param value
* value of the string
* @return string value of the field or empty string if string is null
*/
public String valueOf(String value) {
return (value == null) ? "" : value;
}
/**
* Check if input data is correct
*
* @return true if input is correct, else otherwise
*/
public boolean checkCorrect() {
boolean correct = true;
if (name == null || name.equals("")) {
validationMessages.put("name", Labels.getLabel(EMPTY_TITLE));
correct = false;
}
if (componentName == null || componentName.equals("")) {
validationMessages.put("componentName", Labels.getLabel(EMPTY_NAME));
correct = false;
}
return correct;
}
// getters & setters for web-form
/**
* Returns the title for current component
*
* @return name value from web-form
*/
public String getName() {
return name;
}
/**
* Sets the title for the current component
*
* @param name
* value to set
*/
public void setName(String name) {
this.name = name;
}
/**
* Returns the description for the current component
*
* @return description value from web-form
*/
public String getDescription() {
return description;
}
/**
* Sets the description for the current component
*
* @param description
* to set on web-form
*/
public void setDescription(String description) {
this.description = description;
}
/**
* Returns the name of the current component
*
* @return component name value from web-form
*/
public String getComponentName() {
return componentName;
}
/**
* Sets the name for current component
*
* @param componentName
* new component name value on web-form
*/
public void setComponentName(String componentName) {
this.componentName = componentName;
}
/**
* Returns validation messages for data input
*
* @return validation messages
*/
public Map<String, String> getValidationMessages() {
return validationMessages;
}
// getter and setter for current component we edit
/**
* Gets the current component we edit
*
* @return current component
*/
public Component getCurrentComponent() {
return currentComponent;
}
/**
* Sets the current component we edit
*
* @param currentComponent
* - to set
*/
public void setCurrentComponent(Component currentComponent) {
this.currentComponent = currentComponent;
}
/**
* Returns caption from the web-form
*
* @return caption
*/
public String getCaption() {
return caption;
}
/**
* Sets the current caption
*
* @param caption
* - to set on web-form
*/
public void setCaption(String caption) {
this.caption = caption;
}
/**
* Returns post preview size from the web-form
*
* @return post preview size
*/
public String getPostPreviewSize() {
return postPreviewSize;
}
/**
* Sets the current component we edit
*
* @param postPreviewSize
* - to set on web-form
*/
public void setPostPreviewSize(String postPreviewSize) {
this.postPreviewSize = postPreviewSize;
}
/**
* Returns session timeout value from the web-form
*
* @return session timeout
*/
@NotEmpty(message = "Last name can not be null")
public String getSessionTimeout() {
return sessionTimeout;
}
/**
* Sets session timeout
*
* @param sessionTimeout
* - to set on web-form
*/
public void setSessionTimeout(String sessionTimeout) {
this.sessionTimeout = sessionTimeout;
}
}
|
// TODO: Also add information on how to contact you by electronic and paper mail.
package com.github.vrpolak.q10sk.reference.implementation.api;
/**
* Object used for running q10sk programs.
*
* <p>The behavior corresponds to an immutable object
* whose method mutates some of given arguments.
* Implementations are free to contain mutable data themselves,
* for example various caches.
*
* @author Vratko Polak
*/
public interface Q10skRunner {
/*
* Run program defined by state, calling consumer and producer for output and input repsectively.
*
* <p>If this returns, the program reached halted state.
*
* @param state the initial state of the program, never changed
* @param consumer the consumer to be called when the program want to output, mutated on call
* @param producer the producer to call when the program requires input, mutated on cal
*/
void run(final Q10skStateTreeRootNode state, final BitConsumer consumer, final BitProducer producer);
}
|
package org.eclipse.mylar.zest.core.internal.gefx;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.eclipse.draw2d.ColorConstants;
import org.eclipse.draw2d.FigureCanvas;
import org.eclipse.draw2d.geometry.Dimension;
import org.eclipse.gef.DefaultEditDomain;
import org.eclipse.gef.EditDomain;
import org.eclipse.gef.EditPart;
import org.eclipse.gef.MouseWheelHandler;
import org.eclipse.gef.MouseWheelZoomHandler;
import org.eclipse.gef.ui.parts.ScrollingGraphicalViewer;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.DisposeEvent;
import org.eclipse.swt.events.DisposeListener;
import org.eclipse.swt.events.PaintEvent;
import org.eclipse.swt.events.PaintListener;
import org.eclipse.swt.widgets.Canvas;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.ui.PlatformUI;
/**
*
* @author Ian Bull
* @author Chris Callendar
*/
public abstract class NonThreadedGraphicalViewer extends ScrollingGraphicalViewer {
private List revealListeners = null;
/**
* ThreadedGraphicalViewer constructor.
* @param parent The composite that this viewer will be added to.
*/
public NonThreadedGraphicalViewer(Composite parent) {
super();
revealListeners = new ArrayList(1);
// create the FigureCanvas
createControl(parent);
EditDomain ed = new DefaultEditDomain( null );
ed.addViewer( this );
setEditDomain( ed );
hookControl();
getFigureCanvas().setScrollBarVisibility(FigureCanvas.NEVER);
getControl().addPaintListener(new PaintListener() {
public void paintControl(PaintEvent e) {
if (!revealListeners.isEmpty()) {
// Go through the reveal list and let everyone know that the view
// is now available. Remove the listeners so they are only called once!
Iterator iterator = revealListeners.iterator();
while (iterator.hasNext() ) {
RevealListener reveallisetner = (RevealListener) iterator.next();
reveallisetner.revealed(getControl());
iterator.remove();
}
}
}
});
getControl().addDisposeListener(new DisposeListener() {
public void widgetDisposed(DisposeEvent e) {
}
});
((Canvas)getControl()).setBackground( ColorConstants.white );
// Scroll-wheel Zoom
setProperty(MouseWheelHandler.KeyGenerator.getKey(SWT.MOD1), MouseWheelZoomHandler.SINGLETON);
}
/*
* (non-Javadoc)
* @see org.eclipse.gef.ui.parts.ScrollingGraphicalViewer#reveal(org.eclipse.gef.EditPart)
*/
public void reveal(EditPart part) {
// @tag rootEditPart : Don't reveal root edit parts
if (!(part instanceof GraphRootEditPart))
super.reveal(part);
}
private class MyRunnable implements Runnable{
boolean isVisible;
public void run() { isVisible = getControl().isVisible();}
}
/**
* Adds a reveal listener to the view. Note: A reveal listener will
* only every be called ONCE!!! even if a view comes and goes. There
* is no remove reveal listener.
* @param revealListener
*/
public void addRevealListener( final RevealListener revealListener ) {
MyRunnable myRunnable = new MyRunnable();
PlatformUI.getWorkbench().getDisplay().syncExec( myRunnable);
if ( myRunnable.isVisible )
revealListener.revealed( (Composite)getControl() );
else
revealListeners.add(revealListener);
}
/**
* Does some initializing of the viewer.
*/
protected abstract void configureGraphicalViewer();
/**
* Sets the contents of the viewer and configures the graphical viewer.
* @param model
*/
public void setContents(Object model) {
this.configureGraphicalViewer();
super.setContents(model);
//@tag zest.experimental.contents : publish a property change that the model has changed. This will allow linked viewers to update.
setProperty(IZestViewerProperties.GRAPH_VIEWER_CONTENTS, model);
}
/**
* Updates the contents <b>without</b> configuring the graphical viewer.
* Only call this if the graphical viewer has already be configured.
* @param model
*/
public void updateContents(Object model) {
super.setContents(model);
//@tag zest.experimental.contents : publish a property change that the model has changed. This will allow linked viewers to update.
setProperty(IZestViewerProperties.GRAPH_VIEWER_CONTENTS, model);
}
/**
* Gets the absolute size of the canvas.
* @return Dimension in absolute coords
*/
public Dimension getCanvasSize() {
Dimension dim = new Dimension(getFigureCanvas().getSize());
dim.shrink(getFigureCanvas().getBorderWidth(), getFigureCanvas().getBorderWidth());
return dim;
}
/**
* Gets the translated size of the canvas.
* @return Dimension relative
*/
public Dimension getTranslatedCanvasSize() {
Dimension dim = getCanvasSize();
//mainCanvas.getViewport().translateToRelative(dim);
return dim;
}
}
|
package org.sagebionetworks.change.workers;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import java.util.Date;
import org.junit.After;
import org.junit.Assume;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.sagebionetworks.StackConfiguration;
import org.sagebionetworks.common.util.progress.ProgressCallback;
import org.sagebionetworks.repo.manager.EntityManager;
import org.sagebionetworks.repo.manager.EntityPermissionsManager;
import org.sagebionetworks.repo.model.AccessControlList;
import org.sagebionetworks.repo.model.AuthorizationConstants.BOOTSTRAP_PRINCIPAL;
import org.sagebionetworks.repo.model.Folder;
import org.sagebionetworks.repo.model.Project;
import org.sagebionetworks.repo.model.UserInfo;
import org.sagebionetworks.repo.model.jdo.KeyFactory;
import org.sagebionetworks.repo.model.table.EntityDTO;
import org.sagebionetworks.repo.model.util.AccessControlListUtil;
import org.sagebionetworks.table.cluster.ConnectionFactory;
import org.sagebionetworks.table.cluster.TableIndexDAO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import com.google.common.collect.Lists;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "classpath:test-context.xml" })
public class EntityHierarchyChangeWorkerIntegrationTest {
private static final int MAX_WAIT_MS = 30*1000;
@Autowired
StackConfiguration config;
@Autowired
EntityManager entityManager;
@Autowired
ConnectionFactory tableConnectionFactory;
@Autowired
EntityPermissionsManager entityPermissionsManager;
TableIndexDAO indexDao;
@Mock
ProgressCallback mockProgressCallback;
UserInfo adminUser;
Long userId;
Project project;
Folder folder;
Folder child;
@Before
public void before(){
// Only run this test if the table feature is enabled.
Assume.assumeTrue(config.getTableEnabled());
// this is still an integration test even though a mock progress is used.
MockitoAnnotations.initMocks(this);
userId = BOOTSTRAP_PRINCIPAL.THE_ADMIN_USER.getPrincipalId();
adminUser = new UserInfo(true, userId);
indexDao = tableConnectionFactory.getAllConnections().get(0);
project = new Project();
project.setName("parent");
String id = entityManager.createEntity(adminUser, project, null);
project = entityManager.getEntity(adminUser, id, Project.class);
// create a folder
folder = new Folder();
folder.setName("folder");
folder.setParentId(project.getId());
id = entityManager.createEntity(adminUser, folder, null);
folder = entityManager.getEntity(adminUser, id, Folder.class);
// create a child
child = new Folder();
child.setName("child");
child.setParentId(folder.getId());
id = entityManager.createEntity(adminUser, child, null);
child = entityManager.getEntity(adminUser, id, Folder.class);
}
@After
public void after(){
if(project != null){
entityManager.deleteEntity(adminUser, project.getId());
}
}
@Test
public void testRoundTrip() throws InterruptedException{
// wait for the child to be replicated
EntityDTO replicatedChild = waitForEntityDto(child.getId());
assertNotNull(replicatedChild);
assertEquals(KeyFactory.stringToKey(project.getId()), replicatedChild.getBenefactorId());
// Delete the replicated data
indexDao.deleteEntityData(mockProgressCallback , Lists.newArrayList(KeyFactory.stringToKey(child.getId())));
// Add an ACL to the folder to trigger a hierarchy change
AccessControlList acl = AccessControlListUtil.createACLToGrantEntityAdminAccess(folder.getId(), adminUser, new Date());
entityPermissionsManager.overrideInheritance(acl, adminUser);
// the update should trigger the replication of the child
replicatedChild = waitForEntityDto(child.getId());
assertNotNull(replicatedChild);
// the benefactor should now the folder.
assertEquals(KeyFactory.stringToKey(folder.getId()), replicatedChild.getBenefactorId());
}
/**
* Helper to wait for replicated data to appear.
* @param entityId
* @return
* @throws InterruptedException
*/
public EntityDTO waitForEntityDto(String entityId) throws InterruptedException{
long startTimeMS = System.currentTimeMillis();
while(true){
EntityDTO entityDto = indexDao.getEntityData(KeyFactory.stringToKey(entityId));
if(entityDto != null){
return entityDto;
}
System.out.println("Waiting for entity data to be replicated for id: "+entityId);
Thread.sleep(2000);
assertTrue("Timed-out waiting for entity data to be replicated.",System.currentTimeMillis()-startTimeMS < MAX_WAIT_MS);
}
}
}
|
package org.tuxdevelop.spring.data.solr.demo.repository;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.geo.Distance;
import org.springframework.data.geo.Point;
import org.springframework.data.solr.core.query.result.*;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.tuxdevelop.spring.data.solr.demo.configuration.ITConfiguration;
import org.tuxdevelop.spring.data.solr.demo.domain.Store;
import org.tuxdevelop.spring.data.solr.demo.util.SolrInitializer;
import java.util.Collection;
import java.util.LinkedList;
import java.util.List;
import static org.assertj.core.api.Assertions.assertThat;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = ITConfiguration.class)
public class StoreRepositoryIT {
@Autowired
private StoreRepository storeRepository;
@Autowired
private SolrInitializer solrInitializer;
/*
* init solr
*/
@Before
public void init() throws Exception {
solrInitializer.importStarbucks();
}
/*
* Search IT
*/
@Test
public void findByNameIT() {
final String nameToFind = "Steaming Kettle";
final Collection<Store> stores = storeRepository.findByName(nameToFind);
assertThat(stores).isNotEmpty();
assertThat(stores).hasSize(1);
}
@Test
public void findByNameQueryIT() {
final String nameToFind = "Steaming Kettle";
final Collection<Store> stores = storeRepository.findByNameQuery(nameToFind);
assertThat(stores).isNotEmpty();
assertThat(stores).hasSize(1);
}
@Test
public void findByNameFilterQueryIT() {
final String nameToFind = "Steaming Kettle";
final Collection<Store> stores = storeRepository.findByNameFilterQuery(nameToFind);
assertThat(stores).isNotEmpty();
assertThat(stores).hasSize(1);
}
@Test
public void findStoreByNameFilterQueryIT() {
final String nameToFind = "Steaming Kettle";
final Collection<Store> stores = storeRepository.findStoreByNameFilterQuery(nameToFind);
assertThat(stores).isNotEmpty();
assertThat(stores).hasSize(1);
}
@Test
public void findByLocationNearIT() {
final Point point = new Point(43, -71);
final Distance distance = new Distance(10);
final Collection<Store> stores = storeRepository.findByLocationNear(point, distance);
assertThat(stores).isNotEmpty();
assertThat(stores).hasSize(2);
for (Store store : stores) {
System.out.println(store);
}
}
@Test
public void findByProductsInIT() {
final Collection<String> products = new LinkedList<>();
products.add("Lunch");
products.add("Oven-warmed Food");
products.add("Reserve Amenity");
final Collection<Store> stores = storeRepository.findByProductsIn(products);
assertThat(stores).isNotEmpty();
System.out.println("Size: " + stores.size());
}
@Test
public void findByPoductsInAndLocationNearIT() {
final Collection<String> products = new LinkedList<>();
products.add("Lunch");
products.add("Oven-warmed Food");
products.add("Reserve Amenity");
final Point point = new Point(43, -71);
final Distance distance = new Distance(10);
final Collection<Store> stores = storeRepository.findByProductsInAndLocationNear(products, point, distance);
assertThat(stores).hasSize(1);
}
/*
* Solr Operations IT
*/
@Test
public void updateProductsIT() {
final String newProduct = "1&1 Handy Flat!";
final String id = "1";
final Store store = storeRepository.findOne(id);
assertThat(store).isNotNull();
final Collection<String> products = store.getProducts();
final Collection<String> newProducts = new LinkedList<>();
newProducts.add(newProduct);
storeRepository.updateProducts(id, newProducts);
final Store updatedStore = storeRepository.findOne(id);
assertThat(updatedStore).isNotNull();
final Collection<String> updatedProducts = updatedStore.getProducts();
assertThat(products).isNotEqualTo(updatedProducts);
assertThat(updatedProducts).contains(newProduct);
}
/*
* Facetting
*/
@Test
public void findByZipCodeFacetOnProductsIT() {
final String zipCode = "03833-2105";
final FacetPage<Store> response = storeRepository.findByZipCodeFacetOnProducts(zipCode, new
PageRequest(0, 20));
assertThat(response).isNotNull();
assertThat(response.getContent()).isNotEmpty();
assertThat(response.getContent()).hasSize(3);
for (final Store store : response.getContent()) {
System.err.println(store);
}
Page<FacetFieldEntry> page = response.getFacetResultPage("products");
final int size = page.getSize();
System.err.println("size:" + size);
final Page<FacetFieldEntry> facetResultPage = response.getFacetResultPage("products");
List<FacetFieldEntry> content = facetResultPage.getContent();
System.err.println("content.size:" + content.size());
for (final FacetFieldEntry facetFieldEntry : content) {
System.err.println("Found: " + facetFieldEntry.getValue());
}
}
@Test
public void findFacetOnNameIT() {
final List<String> products = new LinkedList<>();
products.add("Lunch");
final FacetPage<Store> response = storeRepository.findFacetOnName(products, new PageRequest(0, 20));
assertThat(response).isNotNull();
assertThat(response.getContent()).isNotEmpty();
for (final Store store : response.getContent()) {
System.err.println(store);
}
final Page<FacetFieldEntry> page = response.getFacetResultPage("name");
final int size = page.getSize();
System.err.println("size:" + size);
final Page<FacetFieldEntry> facetResultPage = response.getFacetResultPage("name");
List<FacetFieldEntry> content = facetResultPage.getContent();
System.err.println("content.size:" + content.size());
for (final FacetFieldEntry facetFieldEntry : content) {
System.err.println("Found: " + facetFieldEntry.getValue());
}
}
@Test
public void findFacetOnNameSolrTemplateIT() {
final List<String> products = new LinkedList<>();
products.add("Lunch");
final FacetPage<Store> response = storeRepository.findFacetOnNameSolrTemplate(products);
assertThat(response).isNotNull();
assertThat(response.getContent()).isNotEmpty();
for (final Store store : response.getContent()) {
System.err.println(store);
}
final Page<FacetFieldEntry> page = response.getFacetResultPage("name");
final int size = page.getSize();
System.err.println("size:" + size);
final Page<FacetFieldEntry> facetResultPage = response.getFacetResultPage("name");
List<FacetFieldEntry> content = facetResultPage.getContent();
System.err.println("content.size:" + content.size());
for (final FacetFieldEntry facetFieldEntry : content) {
System.err.println("Found: " + facetFieldEntry.getValue());
}
}
@Test
public void findByFacetOnProductsIT() {
final FacetPage<Store> response = storeRepository.findByFacetOnProducts(new
PageRequest(0, 100));
assertThat(response).isNotNull();
assertThat(response.getContent()).isNotEmpty();
assertThat(response.getContent()).hasSize(100);
for (final Store store : response.getContent()) {
System.err.println(store);
}
final Page<FacetFieldEntry> page = response.getFacetResultPage("products");
final int size = page.getSize();
System.err.println("size:" + size);
final Page<FacetFieldEntry> facetResultPage = response.getFacetResultPage("products");
List<FacetFieldEntry> content = facetResultPage.getContent();
System.err.println("content.size:" + content.size());
for (final FacetFieldEntry facetFieldEntry : content) {
System.err.println("Found: " + facetFieldEntry.getValue());
}
}
/*
* Grouping
*/
@Test
public void groupByZipCodeIT() {
final String lunch = "Lunch";
final List<String> products = new LinkedList<>();
products.add(lunch);
final GroupPage<Store> response = storeRepository.groupByZipCode(products);
System.err.println("
GroupResult<Store> groupResult = response.getGroupResult("zipCode");
final Page<GroupEntry<Store>> groupEntries = groupResult.getGroupEntries();
for (final GroupEntry<Store> groupEntry : groupEntries) {
final String groupValue = groupEntry.getGroupValue();
System.err.println("groupValue: " + groupValue);
final List<Store> groupContet = groupEntry.getResult().getContent();
System.err.println("Members of the group: ");
for (final Store store : groupContet) {
System.err.println(store);
}
}
}
}
|
package org.wyona.yanel.impl.resources;
import org.wyona.yanel.core.Path;
import org.wyona.yanel.core.Resource;
import org.wyona.yanel.core.ResourceConfiguration;
import org.wyona.yanel.core.ResourceTypeDefinition;
import org.wyona.yanel.core.ResourceTypeRegistry;
import org.wyona.yanel.core.api.attributes.CreatableV2;
import org.wyona.yanel.core.api.attributes.ViewableV2;
import org.wyona.yanel.core.attributes.viewable.View;
import org.wyona.yanel.core.attributes.viewable.ViewDescriptor;
import org.wyona.yanel.core.navigation.Node;
import org.wyona.yanel.core.navigation.Sitetree;
import org.wyona.yanel.core.serialization.SerializerFactory;
import org.wyona.yanel.core.source.ResourceResolver;
import org.wyona.yanel.core.transformation.I18nTransformer2;
import org.wyona.yanel.core.transformation.XIncludeTransformer;
import org.wyona.yanel.core.util.PathUtil;
import org.wyona.yanel.core.util.ResourceAttributeHelper;
import org.apache.log4j.Category;
import org.apache.xml.resolver.tools.CatalogResolver;
import org.apache.xml.serializer.Serializer;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileReader;
import java.util.Enumeration;
import javax.servlet.http.HttpServletRequest;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.sax.SAXResult;
import javax.xml.transform.sax.SAXTransformerFactory;
import javax.xml.transform.sax.TransformerHandler;
import javax.xml.transform.stream.StreamSource;
import org.apache.avalon.framework.configuration.Configuration;
import org.apache.avalon.framework.configuration.ConfigurationUtil;
import org.w3c.dom.Document;
import org.xml.sax.InputSource;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.XMLReaderFactory;
public class ResourceCreatorResource extends Resource implements ViewableV2{
private static Category log = Category.getInstance(ResourceCreatorResource.class);
private boolean ajaxBrowser = false;
public ResourceCreatorResource() {
}
public boolean exists() {
return true;
}
public long getSize() {
return -1;
}
public String getMimeType(String viewId) {
if (viewId != null && viewId.equals("source")) return "application/xml";
return "application/xhtml+xml";
}
public View getView(String viewId) {
if(request.getHeader("User-Agent").indexOf("rv:1.7") < 0) {
ajaxBrowser = true;
}
View view = new View();
String mimeType = getMimeType(viewId);
view.setMimeType(mimeType);
try {
org.wyona.yarep.core.Repository repo = getRealm().getRepository();
if (viewId != null && viewId.equals("source")) {
view.setInputStream(new java.io.StringBufferInputStream(getScreen()));
view.setMimeType("application/xml");
return view;
}
String[] xsltPath = getXSLTPath(getPath());
if (xsltPath != null) {
// create reader:
XMLReader xmlReader = XMLReaderFactory.createXMLReader();
CatalogResolver catalogResolver = new CatalogResolver();
xmlReader.setEntityResolver(catalogResolver);
// create xslt transformer:
SAXTransformerFactory tf = (SAXTransformerFactory)TransformerFactory.newInstance();
TransformerHandler[] xsltHandlers = new TransformerHandler[xsltPath.length];
for (int i = 0; i < xsltPath.length; i++) {
xsltHandlers[i] = tf.newTransformerHandler(new StreamSource(repo.getNode(xsltPath[i]).getInputStream()));
xsltHandlers[i].getTransformer().setParameter("yanel.path.name", PathUtil.getName(getPath()));
xsltHandlers[i].getTransformer().setParameter("yanel.path", getPath());
xsltHandlers[i].getTransformer().setParameter("yanel.back2context", PathUtil.backToContext(realm, getPath()));
xsltHandlers[i].getTransformer().setParameter("yarep.back2realm", PathUtil.backToRealm(getPath()));
xsltHandlers[i].getTransformer().setParameter("language", getRequestedLanguage());
}
// create i18n transformer:
I18nTransformer2 i18nTransformer = new I18nTransformer2("global", getRequestedLanguage(), getRealm().getDefaultLanguage());
i18nTransformer.setEntityResolver(catalogResolver);
// create xinclude transformer:
XIncludeTransformer xIncludeTransformer = new XIncludeTransformer();
ResourceResolver resolver = new ResourceResolver(this);
xIncludeTransformer.setResolver(resolver);
// create serializer:
Serializer serializer = SerializerFactory.getSerializer(SerializerFactory.XHTML_STRICT);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
// chain everything together (create a pipeline):
xmlReader.setContentHandler(xsltHandlers[0]);
for (int i=0; i<xsltHandlers.length-1; i++) {
xsltHandlers[i].setResult(new SAXResult(xsltHandlers[i+1]));
}
xsltHandlers[xsltHandlers.length-1].setResult(new SAXResult(xIncludeTransformer));
xIncludeTransformer.setResult(new SAXResult(i18nTransformer));
i18nTransformer.setResult(new SAXResult(serializer.asContentHandler()));
serializer.setOutputStream(baos);
// execute pipeline:
xmlReader.parse(new InputSource(new java.io.StringBufferInputStream(getScreen())));
// write result into view:
view.setInputStream(new ByteArrayInputStream(baos.toByteArray()));
return view;
} else {
log.debug("Mime-Type: " + mimeType);
view.setInputStream(new java.io.StringBufferInputStream(getScreen()));
return view;
}
} catch(Exception e) {
log.error(e + " (" + getPath() + ", " + getRealm() + ")", e);
}
view.setInputStream(new java.io.StringBufferInputStream(getScreen()));
return view;
}
public ViewDescriptor[] getViewDescriptors() {
ViewDescriptor[] vd = new ViewDescriptor[2];
vd[0] = new ViewDescriptor("default");
vd[0].setMimeType(getMimeType(null));
vd[1] = new ViewDescriptor("source");
vd[1].setMimeType(getMimeType("source"));
return vd;
}
/**
* Flow
*/
private String getScreen() {
StringBuffer sb = new StringBuffer("<?xml version=\"1.0\"?>");
sb.append("<html xmlns=\"http:
sb.append("<head><title>create resource</title>");
sb.append("<link rel=\"stylesheet\" type=\"text/css\" href=\"" + PathUtil.getResourcesHtdocsPath(this) + "css/resource-creator.css\"/>");
sb.append("<link rel=\"stylesheet\" type=\"text/css\" href=\"" + PathUtil.getGlobalHtdocsPath(this) + "yanel-css/progressBar.css\"/>");
sb.append("<script src=\"" + PathUtil.getGlobalHtdocsPath(this) + "yanel-js/prototype.js\" type=\"text/javascript\"></script>");
sb.append("<script src=\"" + PathUtil.getGlobalHtdocsPath(this) + "yanel-js/progressBar.js\" type=\"text/javascript\"></script>");
sb.append("<script src=\"" + PathUtil.getGlobalHtdocsPath(this) + "yanel-js/sorttable.js\" type=\"text/javascript\"></script>");
sb.append("<script src=\"" + PathUtil.getResourcesHtdocsPath(this)+ "js/ajaxlookup.js\" type=\"text/javascript\"></script>");
sb.append("</head>");
sb.append("<body>");
HttpServletRequest request = getRequest();
Enumeration parameters = request.getParameterNames();
if (!parameters.hasMoreElements()) {
getSelectResourceTypeScreen(sb);
} else {
if (request.getParameter("save-as") != null) {
// NOTE: Save as has been merged with getResourceScreen because otherwise uploading of data would be rather cumbersome.
//getSaveAsScreen(sb);
getNoSuchScreen(sb);
} else if (request.getParameter("save") != null) {
getSaveScreen(sb);
} else if (request.getParameter("lookup") != null) {
return getLookUp().toString();
} else if (request.getParameter("resource-type") != null) {
getResourceScreen(sb);
} else {
log.info("Fallback ...");
//getNoSuchScreen(sb);
getSelectResourceTypeScreen(sb);
}
}
sb.append("</body>");
sb.append("</html>");
return sb.toString();
}
private void getSelectResourceTypeScreen(StringBuffer sb) {
sb.append("<h4>Create new page (step 0)</h4>");
sb.append("<h2>Select template (resp. resource type)</h2>");
sb.append("<form>");
ResourceTypeRegistry rtr = new ResourceTypeRegistry();
ResourceTypeDefinition[] rtds = getResourceTypeDefinitions();
if (rtds != null) {
sb.append("Template (resp. resource type): <select name=\"resource-type\">");
for (int i = 0; i < rtds.length; i++) {
try {
Resource resource = rtr.newResource(rtds[i].getResourceTypeUniversalName());
if (resource != null && ResourceAttributeHelper.hasAttributeImplemented(resource, "Creatable", "2")) {
sb.append("<option value=\"" + rtds[i].getResourceTypeNamespace() + "::" + rtds[i].getResourceTypeLocalName() + "\">" + getDisplayName(rtds[i].getResourceTypeLocalName(), rtds[i].getResourceTypeNamespace()) + "</option>");
} else {
log.warn("Resource type: " + rtds[i] + " does not implement CreatableV2 interface!");
}
} catch(Exception e) {
log.error(e);
}
}
sb.append("</select>");
} else {
sb.append("<p>No resource types!</p>");
}
sb.append("<br/><input type=\"button\" name=\"Cancel\" value=\"Cancel\" onclick=\"location.href='" + getReferer() + "'\"/>");
sb.append("<input type=\"hidden\" name=\"referer\" value=\"" + getReferer() + "\"/>");
sb.append("<input type=\"submit\" value=\"Next\"/>");
sb.append("</form>");
}
private void getNoSuchScreen(StringBuffer sb) {
sb.append("<p>No such screen!</p>");
}
/**
* Save screen
*/
private void getSaveScreen(StringBuffer sb) {
sb.append("<h4>Create new page (step 2)</h4>");
Path pathOfNewResource = null;
try {
pathOfNewResource = create();
} catch(Exception e) {
log.warn(e.getMessage(), e);
sb.append("<p>Exception: "+e.getMessage()+"</p>");
sb.append("<a href=\"javascript:history.back()\">back</a>");
return;
}
sb.append("<h2>Resource has been created</h2>");
HttpServletRequest request = getRequest();
Enumeration parameters = request.getParameterNames();
if (parameters.hasMoreElements()) {
sb.append("<ul>");
while (parameters.hasMoreElements()) {
String parameter = (String) parameters.nextElement();
if (parameter.indexOf("rp.") == 0) {
sb.append("<li>"+parameter+": "+request.getParameter(parameter)+"</li>");
}
}
sb.append("</ul>");
}
if (log.isDebugEnabled()) log.debug("New Resource: " + PathUtil.backToRealm(getPath()) + ", " + pathOfNewResource);
// NOTE: Back to realm has the form of ./ or ../ or ../../ etc., hence drop the leading slash!
if (pathOfNewResource != null) {
String href = PathUtil.backToRealm(getPath()) + pathOfNewResource.toString().substring(1);
sb.append("<p>New resource can be accessed at: <a href=\"" + href + "\">" + href + "</a></p>");
} else {
sb.append("<p>Please note that no path/URL has been associated with the newly created resource, because it might be some internally used resource.</p>");
}
}
private void getResourceScreen(StringBuffer sb) {
String rtps = getRequest().getParameter("resource-type");
String resNamespace = rtps.substring(0, rtps.indexOf("::"));
String resName = rtps.substring(rtps.indexOf("::") + 2);
ResourceTypeRegistry rtr = new ResourceTypeRegistry();
if (getRequest().getParameter("create-new-folder") != null && !getRequest().getParameter("create-new-folder").equals("")) {
try {
create(getRequest().getParameter("create-new-folder"), getRequest().getParameter("lookin"), "http:
} catch (Exception e) {
sb.append("<p>Could not create folder. Exception: " + e + "</p>");
log.error(e.getMessage(), e);
}
}
try {
String universalName = "<{"+ resNamespace +"}"+ resName +"/>";
log.debug("Universal Name: " + universalName);
Resource resource = rtr.newResource(universalName);
if (resource != null) {
if (ResourceAttributeHelper.hasAttributeImplemented(resource, "Creatable", "2")) {
sb.append("<h4>Create new page (step 1)</h4>");
sb.append("<h2>Enter/Select template (resp. resource) specific parameters and \"Save As\"</h2>");
sb.append("<form enctype=\"multipart/form-data\" method=\"post\">");
sb.append("<p>Template (resp. resource type): " + resName + " ("+resNamespace+")</p>");
// TODO: Add this parameter to the continuation within the session!
sb.append("<input type=\"hidden\" name=\"resource-type\" value=\"" + rtps + "\"/>");
Property[] defaultProperties = getDefaultProperties(resName, resNamespace);
String[] propertyNames = ((CreatableV2) resource).getPropertyNames();
if ((propertyNames != null && propertyNames.length > 0) || defaultProperties != null) {
sb.append("<p>Resource specific properties:</p>");
} else {
sb.append("<p>No resource specific properties!</p>");
}
if (propertyNames != null && propertyNames.length > 0) {
sb.append("<table border=\"1\">");
for (int i = 0; i < propertyNames.length; i++) {
sb.append("<tr><td>" + propertyNames[i] + ":   </td><td>");
String propertyType = ((CreatableV2) resource).getPropertyType(propertyNames[i]);
if (propertyType != null && propertyType.equals(CreatableV2.TYPE_UPLOAD)) {
sb.append("<input type=\"file\" name=\"rp." + propertyNames[i] + "\"/><br/>");
} else if (propertyType != null && propertyType.equals(CreatableV2.TYPE_SELECT)) {
Object defaultValues = ((CreatableV2) resource).getProperty(propertyNames[i]);
if (defaultValues instanceof java.util.HashMap) {
sb.append("<select name=\"rp." + propertyNames[i] + "\">");
sb.append(" <option value=\"*\">*</option>");
sb.append(" <option value=\"public\">public</option>");
sb.append(" <option value=\"private\">private</option>");
sb.append("</select><br/>");
} else {
sb.append("Exception: Parameter doesn't seem to be a of type SELECT: " + propertyNames[i]);
}
} else if (propertyType != null && propertyType.equals(CreatableV2.TYPE_PASSWORD)) {
//sb.append("<input type=\"file\" name=\"rp." + propertyNames[i] + "\"/><br/>");
Object value = ((CreatableV2) resource).getProperty(propertyNames[i]);
if (value == null) {
sb.append("<input type=\"password\" name=\"rp." + propertyNames[i] + "\" value=\"\" size=\"60\"/><br/>");
} else {
sb.append("<input type=\"password\" name=\"rp." + propertyNames[i] + "\" value=\"" + value + "\" size=\"60\"/><br/>");
}
} else {
log.debug("Let's assume the property is of type text ...");
Object value = ((CreatableV2) resource).getProperty(propertyNames[i]);
if (value == null) {
sb.append("<input type=\"text\" name=\"rp." + propertyNames[i] + "\" value=\"\" size=\"60\"/><br/>");
} else {
sb.append("<input type=\"text\" name=\"rp." + propertyNames[i] + "\" value=\"" + value + "\" size=\"60\"/><br/>");
}
}
sb.append("</td></tr>");
}
sb.append("</table>");
}
if (defaultProperties != null) {
sb.append("<ul>");
for (int i = 0; i < defaultProperties.length; i++) {
sb.append("<li>");
sb.append("Default property: " + defaultProperties[i]);
sb.append("<input type=\"hidden\" name=\"rp." + defaultProperties[i].getName() + "\" value=\"" + defaultProperties[i].getValue() + "\"/>");
sb.append("</li>");
}
sb.append("</ul>");
}
sb.append("<br/><br/>");
sb.append("<div class=\"creatorFileBrowser\">");
sb.append("<table>");
sb.append("<tr><td colspan=\"2\" class=\"fileBrowserHead\">Save as:</td></tr>");
sb.append("<tr><td colspan=\"2\">");
sb.append("<div id=\"lookup\">");
sb.append(getLookUp());
sb.append("</div>");
sb.append("</td></tr>");
sb.append("<tr><td colspan=\"2\" class=\"fileBrowserNewName\">");
String createName = getRequest().getParameter("create-name");
if (createName != null) {
sb.append("New name: <input type=\"text\" name=\"create-name\" value=\"" + createName + "\"/>");
} else {
sb.append("New name: <input type=\"text\" name=\"create-name\"/>");
}
sb.append("</td></tr>");
sb.append("<tr>");
sb.append("<td>");
sb.append("<input type=\"button\" name=\"Cancel\" value=\"Cancel\" onclick=\"location.href='" + getReferer() + "'\"/>");
sb.append("<input type=\"hidden\" name=\"referer\" value=\"" + getReferer() + "\"/>");
sb.append("</td>");
sb.append("<td align=\"right\">");
sb.append("<input type=\"submit\" value=\"Save new resource\" name=\"save\"/>");
sb.append("</td>");
sb.append("</tr>");
sb.append("</table>");
sb.append("</div>");
sb.append("</form>");
// TODO: Display realm navigation (sitetree, topic map, ...) resp. introduce another step
}
}
} catch (Exception e) {
sb.append("<p>Exception: " + e + "</p>");
log.error(e.getMessage(), e);
}
}
/**
* Creates new resource
* @return Path of new resource
*/
private Path create() throws Exception {
return create(getRequest().getParameter("create-name"), getRequest().getParameter("lookin"), getRequest().getParameter("resource-type"));
}
/**
* Creates new resource
* @param String createName
* @param String lookinPath
* @param String resourceType
* @return Path of new resource
*/
private Path create(String createName, String lookinPath, String resourceType) throws Exception {
org.wyona.yanel.core.map.Realm realm = getRealm();
Path pathOfResourceCreator = new Path(getPath());
org.wyona.commons.io.Path parent = new org.wyona.commons.io.Path(pathOfResourceCreator.toString()).getParent();
Path pathOfNewResource = new Path(getParentOfNewResource(parent, lookinPath).toString() + createName);
if (log.isDebugEnabled()) log.debug("Path of new resource: " + pathOfNewResource);
pathOfNewResource = new Path(removeTooManySlashes(pathOfNewResource.toString()));
if (log.isDebugEnabled()) log.debug("Path of new resource without too many slashes: " + pathOfNewResource);
String rtps = resourceType;
String resNamespace = rtps.substring(0, rtps.indexOf("::"));
String resName = rtps.substring(rtps.indexOf("::") + 2);
Resource newResource = yanel.getResourceManager().getResource(getEnvironment(), realm, pathOfNewResource.toString(), new ResourceConfiguration(resName, resNamespace, null));
if (newResource != null) {
if (ResourceAttributeHelper.hasAttributeImplemented(newResource, "Creatable", "2")) {
createName = ((CreatableV2) newResource).getCreateName(createName);
if (createName != null && createName.equals("")) {
throw new Exception("Please enter a name!");
}
if (createName == null) {
pathOfNewResource = null;
newResource.setPath(null);
} else {
pathOfNewResource = new Path(removeTooManySlashes(getParentOfNewResource(parent, lookinPath).toString()) + createName);
newResource.setPath(pathOfNewResource.toString());
}
((CreatableV2) newResource).create(request);
if (pathOfNewResource != null) {
createResourceConfiguration(newResource);
}
} else {
throw new Exception("creation NOT successfull!");
}
} else {
throw new Exception("creation NOT successful (newResource == null)!");
}
return pathOfNewResource;
}
/**
* Create resource configuration (yanel-rc)
*/
private void createResourceConfiguration(Resource newResource) throws Exception {
StringBuffer rcContent = new StringBuffer("<?xml version=\"1.0\"?>\n\n");
rcContent.append("<yanel:resource-config xmlns:yanel=\"http:
rcContent.append("<yanel:rti name=\"" + newResource.getRTD().getResourceTypeLocalName() + "\" namespace=\"" + newResource.getRTD().getResourceTypeNamespace() + "\"/>\n\n");
java.util.HashMap rtiProperties = ((CreatableV2) newResource).createRTIProperties(request);
if (rtiProperties != null) {
if (log.isDebugEnabled()) log.debug(rtiProperties + " " + PathUtil.getRTIPath(newResource.getPath()));
java.util.Iterator iterator = rtiProperties.keySet().iterator();
while (iterator.hasNext()) {
String property = (String) iterator.next();
String value = (String) rtiProperties.get(property);
if (value != null) {
rcContent.append("<yanel:property name=\"" + property + "\" value=\"" + value + "\"/>\n");
if(log.isDebugEnabled()) log.debug("Set Property: " + property + ", " + value);
} else {
log.warn("Property value is null: " + property);
}
}
} else {
log.warn("No RTI properties: " + newResource.getPath());
}
rcContent.append("</yanel:resource-config>");
org.wyona.yarep.core.Repository rcRepo = newResource.getRealm().getRTIRepository();
org.wyona.commons.io.Path newRCPath = new org.wyona.commons.io.Path(PathUtil.getRCPath(newResource.getPath()));
if (log.isDebugEnabled()) log.debug(newRCPath);
org.wyona.yanel.core.util.YarepUtil.addNodes(rcRepo, newRCPath.toString(), org.wyona.yarep.core.NodeType.RESOURCE);
java.io.Writer writer = new java.io.OutputStreamWriter(rcRepo.getNode(newRCPath.toString()).getOutputStream());
writer.write(rcContent.toString());
writer.close();
}
/**
* Get resource type definitions
*/
private ResourceTypeDefinition[] getResourceTypeDefinitions() {
ResourceTypeRegistry rtr = new ResourceTypeRegistry();
ResourceConfiguration rc = getConfiguration();
Document customConfigDoc = rc.getCustomConfiguration();
if (customConfigDoc != null) {
Configuration config = ConfigurationUtil.toConfiguration(customConfigDoc.getDocumentElement());
Configuration resourceTypesConfig = config.getChild("resource-types", false);
if (resourceTypesConfig != null) {
Configuration[] resourceTypeConfigs = resourceTypesConfig.getChildren("resource-type");
if (resourceTypeConfigs.length == 0) return null;
ResourceTypeDefinition[] rtds = new ResourceTypeDefinition[resourceTypeConfigs.length];
for (int i = 0; i < resourceTypeConfigs.length; i++) {
try {
String universalName = "<{"+resourceTypeConfigs[i].getAttribute("namespace")+"}"+resourceTypeConfigs[i].getAttribute("name")+"/>";
rtds[i] = rtr.getResourceTypeDefinition(universalName);
log.debug("Resource Type: " + universalName);
} catch (Exception e) {
log.error(e.getMessage(), e);
return null;
}
}
return rtds;
}
}
ResourceTypeDefinition[] rtds = rtr.getResourceTypeDefinitions();
return rtds;
}
/**
* Get default properties from custom configuration
*/
private Property[] getDefaultProperties(String resName, String resNamespace) {
Document customConfigDoc = getConfiguration().getCustomConfiguration();
if (customConfigDoc != null) {
Configuration config = ConfigurationUtil.toConfiguration(customConfigDoc.getDocumentElement());
Configuration resourceTypesConfig = config.getChild("resource-types", false);
if (resourceTypesConfig != null) {
Configuration[] resourceTypeConfigs = resourceTypesConfig.getChildren("resource-type");
if (resourceTypeConfigs.length == 0) return null;
for (int i = 0; i < resourceTypeConfigs.length; i++) {
try {
if (resourceTypeConfigs[i].getAttribute("namespace").equals(resNamespace) && resourceTypeConfigs[i].getAttribute("name").equals(resName)) {
log.debug("Resource Type Found: " + resName + ", " + resNamespace);
Configuration[] propertyConfigs = resourceTypeConfigs[i].getChildren("property");
Property[] props = new Property[propertyConfigs.length];
for (int k = 0; k < propertyConfigs.length; k++) {
props[k] = new Property(propertyConfigs[k].getAttribute("name"), propertyConfigs[k].getAttribute("value"));
log.debug("Property: " + props[k]);
}
return props;
}
} catch (Exception e) {
log.error(e.getMessage(), e);
return null;
}
}
}
}
return null;
}
/**
* Get the display name from custom configuration
*/
private String getDisplayName(String resName, String resNamespace) {
Document customConfigDoc = getConfiguration().getCustomConfiguration();
if (customConfigDoc != null) {
try {
org.jdom.Document jdomDocument = new org.jdom.input.DOMBuilder().build(customConfigDoc);
org.jdom.xpath.XPath xpath = org.jdom.xpath.XPath.newInstance("/yanel:custom-config/rc:resource-types/rc:resource-type[@name='" + resName + "']/rc:display-name");
xpath.addNamespace("yanel", "http:
xpath.addNamespace("rc", "http:
org.jdom.Element displayNameElement = (org.jdom.Element) xpath.selectSingleNode(jdomDocument);
if (displayNameElement != null) {
// TODO: It seems like document does not contain text nodes ...
if (log.isDebugEnabled()) log.debug("Display name: " + displayNameElement + " :: " + displayNameElement.getText() + " :: " + displayNameElement.getName());
return displayNameElement.getText();
} else {
log.warn("No display name: " + resName);
return resName;
}
} catch (Exception e) {
log.error(e.getMessage(), e);
return resName;
}
}
return resName;
}
/**
* Return sitetree
*/
private StringBuffer getLookUp() {
StringBuffer sb = new StringBuffer("");
//Sitetree sitetree = (Sitetree) getYanel().getBeanFactory().getBean("repo-navigation");
Sitetree sitetree = getRealm().getRepoNavigation();
Node node = null;
String lookinPath = getRequest().getParameter("lookin");
if (lookinPath != null) {
node = sitetree.getNode(getRealm(), lookinPath);
} else {
node = sitetree.getNode(getRealm(), getPath());
}
if (node != null) {
if (node.isCollection()) {
if(log.isDebugEnabled()) log.debug("Is Collection: " + node.getName());
} else if (node.isResource()) {
if (log.isDebugEnabled()) log.debug("Is Resource: " + node.getName());
node = node.getParent();
} else {
log.error("Neither collection nor resource: " + getPath());
}
} else {
log.error("No such path '" + getPath() + "' within sitetree! Root node will be used.");
node = sitetree.getNode(getRealm(), "/");
}
String rtps = getRequest().getParameter("resource-type");
String resNamespace = rtps.substring(0, rtps.indexOf("::"));
String resName = rtps.substring(rtps.indexOf("::") + 2);
sb.append("<table id=\"resourceCreatorSaveAsTable\">");
sb.append("<tr><td>Look in: " + node.getPath() + "   </td><td>New folder: <input type=\"text\" name=\"create-new-folder\"/> <input type=\"image\" src=\"" + PathUtil.getGlobalHtdocsPath(this) + "yanel-img/icons/folder-new.png\" alt=\"make a new folder\"/> ");
String parent = "/";
if (!node.getPath().equals("/")) {
parent = new org.wyona.commons.io.Path(node.getPath()).getParent().toString();
}
if (log.isDebugEnabled()) log.debug("Parent: " + parent);
if (ajaxBrowser) {
sb.append("<a href=\"JavaScript:ajaxlookup('" + resNamespace + "::" + resName + "', '" + parent + "')\"><img src=\"" + PathUtil.getGlobalHtdocsPath(this) + "yanel-img/icons/go-up.png\" alt=\"go up\" border=\"0\"/></a>");
} else {
sb.append("<a href=\"?lookin=" + parent + "&resource-type=" + resNamespace + "::" + resName + "\"><img src=\"" + PathUtil.getGlobalHtdocsPath(this) + "yanel-img/icons/go-up.png\" alt=\"go up\" border=\"0\"/></a>");
}
sb.append("</td></tr>");
sb.append("<tr><td colspan=\"2\">");
sb.append("<div id=\"lookupfiles\">");
sb.append("<table id=\"lookupfilesTable\" class=\"sortable\">");
sb.append("<thead>");
sb.append("<tr><th>Type</th><th>Name</th><th>Resource Type</th></tr>");
sb.append("</thead>");
sb.append("<tbody>");
Node[] children = node.getChildren();
for (int i = 0; i < children.length; i++) {
String resourceTypeName;
try {
resourceTypeName = yanel.getResourceManager().getResource(getEnvironment(), realm, children[i].getPath()).getResourceTypeLocalName();
} catch (Exception e) {
log.error(e.getMessage(), e);
resourceTypeName = "?";
}
if (children[i].isCollection()) {
// TODO: Also append resource specific parameters (AJAX ...)
if (ajaxBrowser) {
sb.append("<tr><td sorttable_customkey=\"Collection\"><a href=\"JavaScript:ajaxlookup('" + resNamespace + "::" + resName + "', '" + node.getPath() + children[i].getName() + "/')\"><img class=\"lookupicon\" src=\"" + PathUtil.getGlobalHtdocsPath(this) + "yanel-img/icons/folder.png\" alt=\"Collection:\"/></a></td><td><a href=\"JavaScript:ajaxlookup('" + resNamespace + "::" + resName + "', '" + node.getPath() + children[i].getName() + "/')\">" + children[i].getName() + "</a></td><td>" + resourceTypeName + "</td></tr>");
} else {
sb.append("<tr><td sorttable_customkey=\"Collection\"><a href=\"?lookin=" + node.getPath() + children[i].getName() + "/&resource-type=" + resNamespace + "::" + resName + "\"><img class=\"lookupicon\" src=\"" + PathUtil.getGlobalHtdocsPath(this) + "yanel-img/icons/folder.png\" alt=\"Collection:\"/></a></td><td><a href=\"?lookin=" + node.getPath() + children[i].getName() + "/&resource-type=" + resNamespace + "::" + resName + "\">" + children[i].getName() + "</a></td><td>" + resourceTypeName + "</td></tr>");
}
} else if (children[i].isResource()) {
sb.append("<tr><td sorttable_customkey=\"Resource\"><img class=\"lookupicon\" src=\"" + PathUtil.getGlobalHtdocsPath(this) + "yanel-img/icons/text-x-generic.png\" alt=\"Resource:\"/></td><td>"+children[i].getName()+"</td><td>" + resourceTypeName + "</td></tr>");
} else {
sb.append("<tr><td>?</td><td>"+children[i].getName()+"</td><td>-</td></tr>");
}
}
sb.append("</tbody>");
sb.append("</table>");
sb.append("<input type=\"hidden\" name=\"lookin\" value=\"" + node.getPath() + "\"/>");
sb.append("</div>");
sb.append("</td></tr>");
sb.append("</table>");
return sb;
}
/**
* Get XSLT path
*/
private String[] getXSLTPath(String path) throws Exception {
String[] xsltPath = getResourceConfigProperties("xslt");
if (xsltPath != null && xsltPath.length > 0) return xsltPath;
log.info("No XSLT Path within: " + path);
return null;
}
/**
* Remove slashes if there are too many, e.g. /foo//bar.html is being transformed into /foo/bar.html
*/
private String removeTooManySlashes(String path) {
StringBuffer sb = new StringBuffer();
boolean previousCharWasSlash = false;
for (int i = 0; i < path.length(); i++) {
char c = path.charAt(i);
if (c == '/' && previousCharWasSlash) {
if (log.isDebugEnabled()) log.debug("Do not append this slash: " + i);
} else {
sb.append(c);
}
if (c == '/') {
previousCharWasSlash = true;
} else {
previousCharWasSlash = false;
}
}
return sb.toString();
}
private Path getParentOfNewResource(org.wyona.commons.io.Path parent, String lookinPath) {
Path parentOfNewResource = null;
if(parent.equals("null")) {
// if pathOfResourceCreator is ROOT
parentOfNewResource = new Path("/" + lookinPath + "/");
} else if(parent.toString().equals("/")){
parentOfNewResource = new Path(parent + "/" + lookinPath + "/");
} else {
parentOfNewResource = new Path("/" + lookinPath + "/");
}
return parentOfNewResource;
}
private String getReferer() {
if(request.getParameter("referer") != null) {
return request.getParameter("referer");
}
if(request.getHeader("referer") != null) {
return replaceEntities(request.getHeader("referer"));
}
return PathUtil.backToRealm(getPath());
}
/**
* Replaces some characters by their corresponding xml entities.
* This method escapes those characters which must not occur in an xml text node.
* @param string
* @return escaped string
*/
public String replaceEntities(String str) {
// there may be some & and some & mixed in the input, so first transform all
// & to & and then transform all & back to &
// this way we don't get double escaped &amp;
str = str.replaceAll("&", "&");
str = str.replaceAll("&", "&");
str = str.replaceAll("<", "<");
return str;
}
}
class Property {
private String name;
private String value;
public Property(String name, String value) {
this.name = name;
this.value = value;
}
public String getName() {
return name;
}
public String getValue() {
return value;
}
public String toString() {
return name + " = " + value;
}
}
|
package org.wyona.yanel.servlet.toolbar.impl;
import javax.servlet.http.HttpServletRequest;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.LogManager;
import org.wyona.security.core.api.Identity;
import org.wyona.yanel.core.Resource;
import org.wyona.yanel.core.api.attributes.VersionableV2;
import org.wyona.yanel.core.map.Map;
import org.wyona.yanel.core.util.PathUtil;
import org.wyona.yanel.core.util.ResourceAttributeHelper;
import org.wyona.yanel.servlet.YanelServlet;
import org.wyona.yanel.servlet.menu.Menu;
import org.wyona.yanel.servlet.toolbar.YanelToolbar;
import org.wyona.yanel.servlet.toolbar.YanelToolbarException;
/**
* The from scratch realm toolbar example, wrapping a {@link Menu}.
*/
public class FromScratchRealmToolbar implements YanelToolbar {
private static Logger log = LogManager.getLogger(FromScratchRealmToolbar.class);
private final Menu menu;
public FromScratchRealmToolbar() {
this.menu = new org.wyona.yanel.servlet.menu.impl.DefaultMenuV2();
}
/**
* @see org.wyona.yanel.servlet.toolbar.YanelToolbar#getToolbarBodyStart(Resource, HttpServletRequest, Map, String)
*/
public String getToolbarBodyStart(Resource resource, HttpServletRequest request, Map map, String reservedPrefix) {
try {
String backToRealm = PathUtil.backToRealm(resource.getPath());
StringBuilder buf = new StringBuilder();
buf.append("<div id=\"yaneltoolbar_headerwrap\">");
buf.append("<div id=\"yaneltoolbar_menu\">");
buf.append(getToolbarMenus(resource, request, map, reservedPrefix));
buf.append("</div>");
buf.append(getInfo(resource, request, map, backToRealm, reservedPrefix));
buf.append("<span id=\"yaneltoolbar_logo\">");
buf.append("<a href=\"http:
+ "/yanel_toolbar_logo.png\" border=\"0\"/></a>");
buf.append("</span>");
buf.append("</div>");
buf.append("<div id=\"yaneltoolbar_middlewrap\">");
return buf.toString();
} catch (RuntimeException e) {
throw e;
} catch (Exception e) {
throw new YanelToolbarException("Couldn't generate toolbar body start markup: " + e.getMessage(), e);
}
}
/**
* @see org/wyona/yanel/servlet/toolbar/YanelToolbar#getToolbarHeader(Resource, HttpServletRequest, Map, String)
*/
public String getToolbarHeader(Resource resource, HttpServletRequest request, Map map, String reservedPrefix) {
String backToRealm = org.wyona.yanel.core.util.PathUtil.backToRealm(resource.getPath());
StringBuilder sb = new StringBuilder();
sb.append("<!-- START: Dynamically added code by " + this.getClass().getName() + " -->");
sb.append(System.getProperty("line.separator"));
sb.append("<link type=\"text/css\" href=\"" + backToRealm + reservedPrefix + "/toolbar.css\" rel=\"stylesheet\"/>");
sb.append(System.getProperty("line.separator"));
sb.append("<style type=\"text/css\" media=\"screen\">");
sb.append(System.getProperty("line.separator"));
sb.append("#yaneltoolbar_menu li li.haschild{ background: lightgrey url(" + backToRealm + reservedPrefix
+ "/yanel-img/submenu.gif) no-repeat 98% 50%;}");
sb.append(System.getProperty("line.separator"));
sb.append("#yaneltoolbar_menu li li.haschild:hover{ background: lightsteelblue url(" + backToRealm + reservedPrefix
+ "/yanel-img/submenu.gif) no-repeat 98% 50%;}");
sb.append("</style>");
sb.append(System.getProperty("line.separator"));
// If browser is Mozilla (gecko engine rv:1.7)
if (request.getHeader("User-Agent").indexOf("rv:1.7") >= 0) {
sb.append("<link type=\"text/css\" href=\"" + backToRealm + reservedPrefix
+ "/toolbarMozilla.css\" rel=\"stylesheet\"/>");
sb.append(System.getProperty("line.separator"));
}
// If browser is IE
if (request.getHeader("User-Agent").indexOf("compatible; MSIE") >= 0
&& request.getHeader("User-Agent").indexOf("Windows") >= 0) {
sb.append("<link type=\"text/css\" href=\"" + backToRealm + reservedPrefix + "/toolbarIE.css\" rel=\"stylesheet\"/>");
sb.append(System.getProperty("line.separator"));
sb.append("<style type=\"text/css\" media=\"screen\">");
sb.append(" body{behavior:url(" + backToRealm + reservedPrefix + "/csshover.htc);font-size:100%;}");
sb.append("</style>");
}
// If browser is IE6
if (request.getHeader("User-Agent").indexOf("compatible; MSIE 6") >= 0
&& request.getHeader("User-Agent").indexOf("Windows") >= 0) {
sb.append("<link type=\"text/css\" href=\"" + backToRealm + reservedPrefix + "/toolbarIE6.css\" rel=\"stylesheet\"/>");
sb.append(System.getProperty("line.separator"));
}
sb.append("<!-- END: Dynamically added code by " + this.getClass().getName() + " -->");
return sb.toString();
}
/**
* @see org.wyona.yanel.servlet.toolbar.YanelToolbar#getToolbarBodyEnd(Resource, HttpServletRequest, Map, String)
*/
public String getToolbarBodyEnd(Resource resource, HttpServletRequest request, Map map, String reservedPrefix) {
return "</div>";
}
/**
* Gets the toolbar menus.
*/
private String getToolbarMenus(Resource resource, HttpServletRequest request, Map map, String reservedPrefix) throws Exception {
return menu.getAllMenus(resource, request, map, reservedPrefix);
}
/**
* Gets information such as realm name, user name, etc.
*/
private String getInfo(Resource resource, HttpServletRequest request, Map map, String backToRealm, String reservedPrefix) throws Exception {
String userLanguage = getUserLanguage(resource);
StringBuilder buf = new StringBuilder();
buf.append("<span id=\"yaneltoolbar_info\">");
//buf.append("Version: " + yanel.getVersion() + "-r" + yanel.getRevision() + "  ");
if (ResourceAttributeHelper.hasAttributeImplemented(resource, "Versionable", "2")) {
VersionableV2 versionableRes = (VersionableV2) resource;
if (versionableRes.isCheckedOut()) {
buf.append(getLabel("page", userLanguage) + ": <b>Locked by " + versionableRes.getCheckoutUserID()
+ "</b> (<a href=\"?" + YanelServlet.YANEL_RESOURCE_USECASE + "=" + YanelServlet.RELEASE_LOCK
+ "\">unlock</a>)  ");
}
}
org.wyona.yarep.core.Node[] nodes = null;
try {
nodes = resource.getRealm().getRepository().getSearcher().searchProperty("workflow-state", "review", "/");
} catch(org.wyona.yarep.core.search.SearchException e) {
log.error(e, e); // INFO: Do not throw exception in order to make it more fault tolerant, for example the SearchException is thrown if no index exists
}
if (nodes != null && nodes.length > 0) {
buf.append("Workflow: <a href=\"" + backToRealm + reservedPrefix + "/workflow-dashboard.html?workflow-state=review\">" + nodes.length + " pages to be reviewed</a>  ");
}
Identity identity = resource.getEnvironment().getIdentity();
if (identity != null && !identity.isWorld()) {
buf.append(getLabel("user", userLanguage) + ": <b><a href=\"" + backToRealm + reservedPrefix + "/users/" + identity.getUsername()
+ ".html\" style=\"font-size: 13px; text-decoration: none;\">" + identity.getAlias() + "</a></b>");
} else {
buf.append(getLabel("user", userLanguage) + ": <b>Not signed in!</b>");
}
buf.append("</span>");
return buf.toString();
}
/**
* Gets user language (order: profile, browser, ...) (Also see
* org/wyona/yanel/servlet/menu/Menu.java)
*/
private String getUserLanguage(Resource resource) throws Exception {
Identity identity = resource.getEnvironment().getIdentity();
String language = resource.getRequestedLanguage();
String userID = identity.getUsername();
if (userID != null) {
String userLanguage = resource.getRealm().getIdentityManager().getUserManager().getUser(userID).getLanguage();
if (userLanguage != null) {
language = userLanguage;
log.debug("Use user profile language: " + language);
} else {
log.debug("Use requested language: " + language);
}
}
return language;
}
/**
* Gets i18n (TODO: Replace this by something more generic)
*
* @param key I18n key
* @param language Language
*/
private static String getLabel(String key, String language) {
if (language.equals("de")) {
if (key.equals("user")) {
return "Benutzer";
} else if (key.equals("page")) {
return "Seite";
} else {
log.warn("Key '" + key + "' not supported yet by requested language '" + language + "'. Fallback to english!");
return getLabel(key, "en");
}
} else if (language.equals("en")) {
if (key.equals("user")) {
return "User";
} else if (key.equals("page")) {
return "Page";
} else {
log.warn("Key '" + key + "' not supported yet!");
return key;
}
} else {
log.warn("Language '" + language + "' not supported yet. Fallback to english!");
return getLabel(key, "en");
}
}
}
|
package org.jboss.as.test.integration.management.cli;
import java.io.IOException;
import org.jboss.arquillian.container.test.api.RunAsClient;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.as.controller.descriptions.ModelDescriptionConstants;
import org.jboss.as.test.integration.management.base.AbstractCliTestBase;
import org.jboss.as.test.integration.management.util.CLIOpResult;
import org.jboss.dmr.ModelNode;
import org.jboss.dmr.ModelType;
import org.junit.AfterClass;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
@RunWith(Arquillian.class)
@RunAsClient
public class WildCardReadsTestCase extends AbstractCliTestBase {
/*
* This address meets a particular set of requirements needed to validate the WFLY-2527 fix:
* 1) the distributed-cache=dist resource does not actually exist. Therefore eviction=XXX child resources also do not
* TBH I'm not certain this aspect is all that critical, but don't blindly remove it.
* 2) There is no ManagementResourceRegistration for eviction=*
* 3) There are MRR's for eviction=XXX, eviction=YYY, etc
* 4) The descriptions for each of those eviction=XXX, eviction=YYY, etc are identical
*
* TODO add some assertions that validate that 1-4 still hold true, in order to ensure the test continues
* to validate the expected behavior
*/
private static final String OP_PATTERN = "/subsystem=infinispan/cache-container=web/distributed-cache=dist/eviction=%s:%s";
private static final String READ_OP_DESC_OP = ModelDescriptionConstants.READ_OPERATION_DESCRIPTION_OPERATION + "(name=%s)";
private static final String READ_RES_DESC_OP = ModelDescriptionConstants.READ_RESOURCE_DESCRIPTION_OPERATION + "(access-control=combined-descriptions,operations=true,recursive=true)";
private static final String EVICTION = "EVICTION";
@BeforeClass
public static void before() throws Exception {
initCLI();
}
@AfterClass
public static void after() throws Exception {
closeCLI();
}
/**
* Tests WFLY-2527 added behavior of supporting read-operation-description for
* wildcard addresses where there is no generic resource registration for the type
*/
@Test
public void testLenientReadOperationDescription() throws IOException {
cli.sendLine(String.format(OP_PATTERN, EVICTION, ModelDescriptionConstants.READ_OPERATION_NAMES_OPERATION));
CLIOpResult opResult = cli.readAllAsOpResult();
Assert.assertTrue(opResult.isIsOutcomeSuccess());
for (ModelNode node : opResult.getResponseNode().get(ModelDescriptionConstants.RESULT).asList()) {
String opPart = String.format(READ_OP_DESC_OP, node.asString());
cli.sendLine(String.format(OP_PATTERN, EVICTION, opPart));
opResult = cli.readAllAsOpResult();
Assert.assertTrue(opResult.isIsOutcomeSuccess());
ModelNode specific = opResult.getResponseNode().get(ModelDescriptionConstants.RESULT);
cli.sendLine(String.format(OP_PATTERN, "*", opPart));
opResult = cli.readAllAsOpResult();
Assert.assertTrue(opResult.isIsOutcomeSuccess());
Assert.assertEquals("mismatch for " + node.asString(), specific, opResult.getResponseNode().get(ModelDescriptionConstants.RESULT));
}
}
/**
* Tests WFLY-2527 fix.
*/
@Test
public void testReadResourceDescriptionNoGenericRegistration() throws IOException {
cli.sendLine(String.format(OP_PATTERN, EVICTION, READ_RES_DESC_OP));
CLIOpResult opResult = cli.readAllAsOpResult();
Assert.assertTrue(opResult.isIsOutcomeSuccess());
ModelNode specific = opResult.getResponseNode().get(ModelDescriptionConstants.RESULT);
cli.sendLine(String.format(OP_PATTERN, "*", READ_RES_DESC_OP));
opResult = cli.readAllAsOpResult();
Assert.assertTrue(opResult.isIsOutcomeSuccess());
ModelNode generic = opResult.getResponseNode().get(ModelDescriptionConstants.RESULT);
Assert.assertEquals(ModelType.LIST, generic.getType());
Assert.assertEquals(1, generic.asInt());
Assert.assertEquals(specific, generic.get(0).get(ModelDescriptionConstants.RESULT));
}
}
|
public class Solution {
public int[] intersection(int[] nums1, int[] nums2) {
Set<Integer> temp = new HashSet<>();
for (int i = 0; i < nums1.length; i++) {
temp.add(nums1[i]);
}
}
List<Integer> numbers = new ArrayList<>();
for (int i = 0; i < nums2.length; i++) {
if (temp.contains(nums2[i]))
{
numbers.add(nums2[i]);
temp.remove(nums2[i]);
}
}
// transfer array
int newArray[] = new int[numbers.size()];
for (int i = 0; i < numbers.size(); i++) {
newArray[i] = numbers.get(i);
}
return newArray;
}
}
|
import java.awt.Point;
import java.awt.event.MouseEvent;
import java.awt.event.MouseWheelEvent;
import java.awt.geom.Point2D;
import javax.media.opengl.GL;
import javax.media.opengl.GLAutoDrawable;
import javax.media.opengl.GLCanvas;
import javax.vecmath.Matrix4f;
import javax.vecmath.Point3d;
import javax.vecmath.Quat4f;
import javax.vecmath.Vector2f;
import javax.vecmath.Vector3f;
/// Extends the simple renderer with a Trackball controller
public class ArcballRenderer extends SimpleRenderer {
private Matrix4f LastRot = new Matrix4f();
private ArcBallHelper arcBall = null;
private Arcball arcball_geo = new Arcball();
/** Controls zoom speed */
float scale_move_ratio = .05f; /// TODO make the zoom ratio exposed!
/** Controls pan speed */
float pan_move_ratio = 1;
public ArcballRenderer(GLCanvas canvas) {
super(canvas);
LastRot.setIdentity();
arcBall = new ArcBallHelper(canvas.getWidth(), canvas.getHeight());
adjust_pan_speed(canvas.getWidth(), canvas.getHeight());
}
/** Make sure panning speed is ~constant
* TODO use it*/
private void adjust_pan_speed(int width, int height){
/// Pan speed adjusted normalized w.r.t. window size
pan_move_ratio = 1.0f / ((float) canvas.getWidth());
// System.out.printf("pan_move_ratio: %f\n", pan_move_ratio);
}
@Override
public void display(GLAutoDrawable drawable) {
GL gl = drawable.getGL();
gl.glClear(GL.GL_COLOR_BUFFER_BIT | GL.GL_DEPTH_BUFFER_BIT);
gl.glMatrixMode(GL.GL_MODELVIEW);
gl.glLoadIdentity();
// Make unit sphere fit loosely
gl.glScaled(.85, .85, .85);
// Arcball rotates, but doesn't translate/scale
gl.glMultMatrixf(super.getRotation(), 0);
arcball_geo.draw(gl);
// Models are also scaled translated
gl.glScaled(getScale(), getScale(), getScale());
gl.glTranslated(getTx(),getTy(),getTz());
for (int i = 0; i < objects.size(); i++)
objects.elementAt(i).draw(gl);
gl.glFlush();
}
@Override // Arcball needs to know about window geometry
public void reshape(GLAutoDrawable drawable, int x, int y, int width, int height) {
super.reshape(drawable, x, y, width, height);
arcBall.setBounds(width, height);
adjust_pan_speed(width,height);
}
@Override
public void mousePressed(MouseEvent mouseEvent) {
switch (mouseEvent.getButton()) {
case MouseEvent.BUTTON1: // Left Mouse
Point MousePt = mouseEvent.getPoint();
LastRot.set(model_matrix);
arcBall.click(MousePt);
default:
return;
}
}
@Override
public void mouseDragged(MouseEvent mouseEvent) {
switch (mouseEvent.getButton()) {
case MouseEvent.BUTTON1: // Left Mouse
// Update the model matrix
Point MousePt = mouseEvent.getPoint();
Quat4f ThisQuat = new Quat4f();
arcBall.drag(MousePt, ThisQuat);
model_matrix.setRotation(ThisQuat);
model_matrix.mul(model_matrix, LastRot);
break;
case MouseEvent.BUTTON2: // Middle Mouse
System.out.printf("TODO: PANNING \n");
break;
default:
return;
}
// Finally refresh the OpenGL window
canvas.display();
}
@Override
public void mouseClicked(MouseEvent event) {
if (event.getClickCount() == 2) {
System.out.println("double clicked");
}
}
@Override
public void mouseWheelMoved(MouseWheelEvent e){
setScale( getScale()*(1 + (scale_move_ratio*e.getWheelRotation()) ));
canvas.display();
}
/**
* The math to implementing ArcBall functionality
*/
class ArcBallHelper {
private static final float Epsilon = 1.0e-5f;
Vector3f StVec; //Saved click vector
Vector3f EnVec; //Saved drag vector
float adjustWidth; //Mouse bounds width
float adjustHeight; //Mouse bounds height
public ArcBallHelper(float NewWidth, float NewHeight) {
StVec = new Vector3f();
EnVec = new Vector3f();
setBounds(NewWidth, NewHeight);
}
public void mapToSphere(Point point, Vector3f vector) {
//Copy paramter into temp point
Vector2f tempPoint = new Vector2f(point.x, point.y);
//Adjust point coords and scale down to range of [-1 ... 1]
tempPoint.x = (tempPoint.x * this.adjustWidth) - 1.0f;
tempPoint.y = 1.0f - (tempPoint.y * this.adjustHeight);
//Compute the square of the length of the vector to the point from the center
float length = (tempPoint.x * tempPoint.x) + (tempPoint.y * tempPoint.y);
//If the point is mapped outside of the sphere... (length > radius squared)
if (length > 1.0f) {
//Compute a normalizing factor (radius / sqrt(length))
float norm = (float) (1.0 / Math.sqrt(length));
//Return the "normalized" vector, a point on the sphere
vector.x = tempPoint.x * norm;
vector.y = tempPoint.y * norm;
vector.z = 0.0f;
} else //Else it's on the inside
{
//Return a vector to a point mapped inside the sphere sqrt(radius squared - length)
vector.x = tempPoint.x;
vector.y = tempPoint.y;
vector.z = (float) Math.sqrt(1.0f - length);
}
}
public void setBounds(float NewWidth, float NewHeight) {
assert((NewWidth > 1.0f) && (NewHeight > 1.0f));
//Set adjustment factor for width/height
adjustWidth = 1.0f / ((NewWidth - 1.0f) * 0.5f);
adjustHeight = 1.0f / ((NewHeight - 1.0f) * 0.5f);
}
//Mouse down
public void click(Point NewPt) {
mapToSphere(NewPt, this.StVec);
}
//Mouse drag, calculate rotation
public void drag(Point NewPt, Quat4f NewRot) {
//Map the point to the sphere
this.mapToSphere(NewPt, EnVec);
//Return the quaternion equivalent to the rotation
if (NewRot != null) {
Vector3f Perp = new Vector3f();
//Compute the vector perpendicular to the begin and end vectors
Perp.cross(StVec,EnVec);
//Compute the length of the perpendicular vector
if (Perp.length() > Epsilon) //if its non-zero
{
//We're ok, so return the perpendicular vector as the transform after all
NewRot.x = Perp.x;
NewRot.y = Perp.y;
NewRot.z = Perp.z;
//In the quaternion values, w is cosine (theta / 2), where theta is rotation angle
NewRot.w = StVec.dot(EnVec);
} else //if its zero
{
//The begin and end vectors coincide, so return an identity transform
NewRot.x = NewRot.y = NewRot.z = NewRot.w = 0.0f;
}
}
}
}
}
|
package pair;
import java.util.function.BiConsumer;
import java.util.function.BiFunction;
import java.util.function.BiPredicate;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.function.ToDoubleBiFunction;
import java.util.function.ToDoubleFunction;
import java.util.function.ToIntBiFunction;
import java.util.function.ToIntFunction;
import java.util.function.ToLongBiFunction;
import java.util.function.ToLongFunction;
import java.util.function.UnaryOperator;
public class Pair<A, B> {
public static <A, B> Pair<A, B> make(final A left, final B right) {
return new Pair<>(left, right);
}
public static <A> Pair<A, A> of(final A item) {
return make(item, item);
}
public final A left;
public final B right;
public final A left() {
return left;
}
public final B right() {
return right;
}
public final Pair<B, A> invert() {
return Pair.make(right, left);
}
protected Pair(final A a, final B b) {
left = a;
right = b;
}
public <R> R intoFun(final BiFunction<A, B, R> fun) {
return fun.apply(left, right);
}
public void intoCon(final BiConsumer<A, B> fun) {
fun.accept(left, right);
}
public <R> R intoFun(final Function<Pair<A, B>, R> fun) {
return fun.apply(this);
}
public void intoCon(final Consumer<Pair<A, B>> fun) {
fun.accept(this);
}
public double intoDouble(final ToDoubleFunction<Pair<A, B>> fun) {
return fun.applyAsDouble(this);
}
public double intoDouble(final ToDoubleBiFunction<A, B> fun) {
return fun.applyAsDouble(left, right);
}
public int intoInt(final ToIntFunction<Pair<A, B>> fun) {
return fun.applyAsInt(this);
}
public int intoInt(final ToIntBiFunction<A, B> fun) {
return fun.applyAsInt(left, right);
}
public long intoLong(final ToLongFunction<Pair<A, B>> fun) {
return fun.applyAsLong(this);
}
public long intoLong(final ToLongBiFunction<A, B> fun) {
return fun.applyAsLong(left, right);
}
public Pair<A, B> intoPair(final UnaryOperator<Pair<A, B>> fun) {
return fun.apply(this);
}
public boolean intoPred(final Predicate<Pair<A, B>> fun) {
return fun.test(this);
}
public boolean intoPred(final BiPredicate<A, B> fun) {
return fun.test(left, right);
}
public <R> Pair<R, B> mapLeft(final Function<A, R> fun) {
return Pair.make(fun.apply(left), right);
}
public <R> Pair<A, R> mapRight(final Function<B, R> fun) {
return Pair.make(left, fun.apply(right));
}
public <R> Pair<R, B> mapLeft(final R neoLiberal) {
return Pair.make(neoLiberal, right);
}
public Pair<A, B> replaceLeft(final A neoLiberal) {
return Pair.make(neoLiberal, right);
}
public <R> Pair<A, R> mapRight(final R altRight) {
return Pair.make(left, altRight);
}
public Pair<A, B> replaceRight(final B altRight) {
return Pair.make(left, altRight);
}
public static final class F {
public static final <A, B> Function<A, Pair<A, B>> partialRight(
final B right) {
return left -> Pair.make(left, right);
}
public static final <A, B> Function<B, Pair<A, B>> partialLeft(
final A left) {
return right -> Pair.make(left, right);
}
public static final <A, B, R> Function<Pair<A, B>, Pair<R, B>> mapLeft(
final Function<A, R> fun) {
return pair -> pair.mapLeft(fun);
}
public static final <A, B, R> Function<Pair<A, B>, Pair<A, R>> mapRight(
final Function<B, R> fun) {
return pair -> pair.mapRight(fun);
}
public static final <A, B, R> Function<Pair<A, B>, Pair<R, B>> mapLeft(
final R neoLiberal) {
return pair -> pair.mapLeft(neoLiberal);
}
public static final <A, B, R> Function<Pair<A, B>, Pair<A, R>> mapRight(
final R altRight) {
return pair -> pair.mapRight(altRight);
}
public static final <A, B> UnaryOperator<Pair<A, B>> replaceLeft(
A neoLiberal) {
return pair -> pair.replaceLeft(neoLiberal);
}
public static final <A, B> UnaryOperator<Pair<A, B>> replaceRight(
B altRight) {
return pair -> pair.replaceRight(altRight);
}
public static final <A, B, R> Function<Pair<A, B>, R> intoFun(
final BiFunction<A, B, R> fun) {
return pair -> pair.intoFun(fun);
}
public static final <A, B> UnaryOperator<Pair<A, B>> intoPair(
final UnaryOperator<Pair<A, B>> fun) {
return pair -> pair.intoFun(fun);
}
public static final <A, B> ToDoubleFunction<Pair<A, B>> intoDouble(
final ToDoubleFunction<Pair<A, B>> fun) {
return pair -> pair.intoDouble(fun);
}
public static final <A, B> ToDoubleFunction<Pair<A, B>> intoDouble(
final ToDoubleBiFunction<A, B> fun) {
return pair -> pair.intoDouble(fun);
}
public static final <A, B> Consumer<Pair<A, B>> intoCon(
final BiConsumer<A, B> fun) {
return pair -> pair.intoCon(fun);
}
public static final <A, B> Predicate<Pair<A, B>> intoPred(
final BiPredicate<A, B> pred) {
return pair -> pair.intoPred(pred);
}
}
}
|
package org.jpos.iso;
import org.jpos.core.Configurable;
import org.jpos.core.Configuration;
import org.jpos.core.ConfigurationException;
import org.jpos.util.*;
import java.io.EOFException;
import java.io.IOException;
import java.io.InterruptedIOException;
import java.io.PrintStream;
import java.lang.ref.WeakReference;
import java.net.*;
import java.util.*;
/**
* Accept ServerChannel sessions and forwards them to ISORequestListeners
* @author Alejandro P. Revilla
* @author Bharavi Gade
* @version $Revision$ $Date$
*/
public class ISOServer extends Observable
implements LogSource, Runnable, Observer, ISOServerMBean, Configurable,
Loggeable, ISOServerSocketFactory
{
int port;
protected ISOChannel clientSideChannel;
ISOPackager clientPackager;
protected Collection clientOutgoingFilters, clientIncomingFilters, listeners;
ThreadPool pool;
public static final int DEFAULT_MAX_THREADS = 100;
public static final String LAST = ":last";
String name;
protected long lastTxn = 0l;
protected Logger logger;
protected String realm;
protected String realmChannel;
protected ISOServerSocketFactory socketFactory = null;
public static final int CONNECT = 0;
public static final int SIZEOF_CNT = 1;
private int[] cnt;
private String[] allow;
private InetAddress bindAddr;
private int backlog;
protected Configuration cfg;
private boolean shutdown = false;
private ServerSocket serverSocket;
private Map channels;
protected boolean ignoreISOExceptions;
/**
* @param port port to listen
* @param clientSide client side ISOChannel (where we accept connections)
* @param pool ThreadPool (created if null)
*/
public ISOServer(int port, ServerChannel clientSide, ThreadPool pool) {
super();
this.port = port;
this.clientSideChannel = clientSide;
this.clientPackager = clientSide.getPackager();
if (clientSide instanceof FilteredChannel) {
FilteredChannel fc = (FilteredChannel) clientSide;
this.clientOutgoingFilters = fc.getOutgoingFilters();
this.clientIncomingFilters = fc.getIncomingFilters();
}
this.pool = (pool == null) ?
new ThreadPool (1, DEFAULT_MAX_THREADS) : pool;
listeners = new Vector();
name = "";
channels = new HashMap();
cnt = new int[SIZEOF_CNT];
}
protected Session createSession (ServerChannel channel) {
return new Session (channel);
}
protected class Session implements Runnable, LogSource {
ServerChannel channel;
String realm;
protected Session(ServerChannel channel) {
this.channel = channel;
realm = ISOServer.this.getRealm() + ".session";
}
public void run() {
setChanged ();
notifyObservers ();
if (channel instanceof BaseChannel) {
LogEvent ev = new LogEvent (this, "session-start");
Socket socket = ((BaseChannel)channel).getSocket ();
realm = realm + "/" + socket.getInetAddress().getHostAddress() + ":"
+ socket.getPort();
try {
checkPermission (socket, ev);
} catch (ISOException e) {
try {
int delay = 1000 + new Random().nextInt (4000);
ev.addMessage (e.getMessage());
ev.addMessage ("delay=" + delay);
ISOUtil.sleep (delay);
socket.close ();
} catch (IOException ioe) {
ev.addMessage (ioe);
}
return;
} finally {
Logger.log (ev);
}
}
try {
for (;;) {
try {
ISOMsg m = channel.receive();
lastTxn = System.currentTimeMillis();
Iterator iter = listeners.iterator();
while (iter.hasNext())
if (((ISORequestListener)iter.next()).process
(channel, m))
break;
}
catch (ISOFilter.VetoException e) {
Logger.log (new LogEvent (this, "VetoException", e.getMessage()));
}
catch (ISOException e) {
if (ignoreISOExceptions) {
Logger.log (new LogEvent (this, "ISOException", e.getMessage()));
} else
throw e;
}
}
} catch (EOFException e) {
// Logger.log (new LogEvent (this, "session-warning", "<eof/>"));
} catch (SocketException e) {
// if (!shutdown)
// Logger.log (new LogEvent (this, "session-warning", e));
} catch (InterruptedIOException e) {
// nothing to log
} catch (Throwable e) {
Logger.log (new LogEvent (this, "session-error", e));
}
try {
channel.disconnect();
} catch (IOException ex) {
Logger.log (new LogEvent (this, "session-error", ex));
}
Logger.log (new LogEvent (this, "session-end"));
}
public void setLogger (Logger logger, String realm) {
}
public String getRealm () {
return realm;
}
public Logger getLogger() {
return ISOServer.this.getLogger();
}
public void checkPermission (Socket socket, LogEvent evt)
throws ISOException
{
if (allow != null && allow.length > 0) {
String ip = socket.getInetAddress().getHostAddress ();
for (int i=0; i<allow.length; i++) {
if (ip.equals (allow[i])) {
evt.addMessage ("access granted, ip=" + ip);
return;
}
}
throw new ISOException ("access denied, ip=" + ip);
}
}
}
/**
* add an ISORequestListener
* @param l request listener to be added
* @see ISORequestListener
*/
public void addISORequestListener(ISORequestListener l) {
listeners.add (l);
}
/**
* remove an ISORequestListener
* @param l a request listener to be removed
* @see ISORequestListener
*/
public void removeISORequestListener(ISORequestListener l) {
listeners.remove (l);
}
/**
* Shutdown this server
*/
public void shutdown () {
shutdown = true;
new Thread ("ISOServer-shutdown") {
public void run () {
shutdownServer ();
if (!cfg.getBoolean ("keep-channels"))
shutdownChannels ();
}
}.start();
}
private void shutdownServer () {
try {
if (serverSocket != null)
serverSocket.close ();
if (pool != null)
pool.close();
} catch (IOException e) {
Logger.log (new LogEvent (this, "shutdown", e));
}
}
private void shutdownChannels () {
Iterator iter = channels.entrySet().iterator();
while (iter.hasNext()) {
Map.Entry entry = (Map.Entry) iter.next();
WeakReference ref = (WeakReference) entry.getValue();
ISOChannel c = (ISOChannel) ref.get ();
if (c != null) {
try {
c.disconnect ();
} catch (IOException e) {
Logger.log (new LogEvent (this, "shutdown", e));
}
}
}
}
private void purgeChannels () {
Iterator iter = channels.entrySet().iterator();
while (iter.hasNext()) {
Map.Entry entry = (Map.Entry) iter.next();
WeakReference ref = (WeakReference) entry.getValue();
ISOChannel c = (ISOChannel) ref.get ();
if (c == null || (!c.isConnected()))
iter.remove ();
}
}
public ServerSocket createServerSocket(int port) throws IOException {
ServerSocket ss = new ServerSocket();
try {
ss.setReuseAddress(true);
ss.bind(new InetSocketAddress(bindAddr, port), backlog);
} catch(SecurityException e) {
ss.close();
throw e;
} catch(IOException e) {
ss.close();
throw e;
}
return ss;
}
public void run() {
ServerChannel channel;
if (socketFactory == null)
socketFactory = this;
serverLoop : while (!shutdown) {
try {
serverSocket = socketFactory.createServerSocket(port);
Logger.log (new LogEvent (this, "iso-server",
"listening on " + (bindAddr != null ? bindAddr + ":" : "port ") + port
+ (backlog > 0 ? " backlog="+backlog : "")
));
while (!shutdown) {
try {
if (pool.getAvailableCount() <= 0) {
try {
serverSocket.close();
} catch (IOException e){
Logger.log (new LogEvent (this, "iso-server", e));
relax();
}
for (int i=0; pool.getIdleCount() == 0; i++) {
if (shutdown) break serverLoop;
if (i % 240 == 0 && cfg.getBoolean("pool-exhaustion-warning", true)) {
LogEvent evt = new LogEvent (this, "warn");
evt.addMessage (
"pool exhausted " + serverSocket.toString()
);
evt.addMessage (pool);
Logger.log (evt);
}
ISOUtil.sleep (250);
}
serverSocket = socketFactory.createServerSocket(port);
}
channel = (ServerChannel) clientSideChannel.clone();
channel.accept (serverSocket);
if ((cnt[CONNECT]++) % 100 == 0)
purgeChannels ();
WeakReference wr = new WeakReference (channel);
channels.put (channel.getName(), wr);
channels.put (LAST, wr);
pool.execute (createSession(channel));
setChanged ();
notifyObservers (this);
if (channel instanceof Observable)
((Observable)channel).addObserver (this);
} catch (SocketException e) {
if (!shutdown) {
Logger.log (new LogEvent (this, "iso-server", e));
relax();
continue serverLoop;
}
} catch (IOException e) {
Logger.log (new LogEvent (this, "iso-server", e));
relax();
}
}
} catch (Throwable e) {
Logger.log (new LogEvent (this, "iso-server", e));
relax();
}
}
}
private void relax() {
try {
Thread.sleep (5000);
} catch (InterruptedException e) { }
}
/**
* associates this ISOServer with a name using NameRegistrar
* @param name name to register
* @see NameRegistrar
*/
public void setName (String name) {
this.name = name;
NameRegistrar.register ("server."+name, this);
}
/**
* @return ISOServer instance with given name.
* @throws NameRegistrar.NotFoundException;
* @see NameRegistrar
*/
public static ISOServer getServer (String name)
throws NameRegistrar.NotFoundException
{
return (ISOServer) NameRegistrar.get ("server."+name);
}
/**
* @return this ISOServer's name ("" if no name was set)
*/
public String getName() {
return this.name;
}
public void setLogger (Logger logger, String realm) {
this.logger = logger;
this.realm = realm;
this.realmChannel = realm + ".channel";
}
public String getRealm () {
return realm;
}
public Logger getLogger() {
return logger;
}
public void update(Observable o, Object arg) {
setChanged ();
notifyObservers (arg);
}
/**
* Gets the ISOClientSocketFactory (may be null)
* @see ISOClientSocketFactory
* @since 1.3.3
*/
public ISOServerSocketFactory getSocketFactory() {
return socketFactory;
}
/**
* Sets the specified Socket Factory to create sockets
* @param socketFactory the ISOClientSocketFactory
* @see ISOClientSocketFactory
* @since 1.3.3
*/
public void setSocketFactory(ISOServerSocketFactory socketFactory) {
this.socketFactory = socketFactory;
}
public int getPort () {
return port;
}
public void resetCounters () {
cnt = new int[SIZEOF_CNT];
lastTxn = 0l;
}
/**
* @return number of connections accepted by this server
*/
public int getConnectionCount () {
return cnt[CONNECT];
}
// ThreadPoolMBean implementation (delegate calls to pool)
public int getJobCount () {
return pool.getJobCount();
}
public int getPoolSize () {
return pool.getPoolSize();
}
public int getMaxPoolSize () {
return pool.getMaxPoolSize();
}
public int getIdleCount() {
return pool.getIdleCount();
}
public int getPendingCount () {
return pool.getPendingCount();
}
public int getActiveConnections () {
return pool.getActiveCount();
}
/**
* @return most recently connected ISOChannel or null
*/
public ISOChannel getLastConnectedISOChannel () {
return getISOChannel (LAST);
}
/**
* @return ISOChannel under the given name
*/
public ISOChannel getISOChannel (String name) {
WeakReference ref = (WeakReference) channels.get (name);
if (ref != null)
return (ISOChannel) ref.get ();
return null;
}
public void setConfiguration (Configuration cfg) throws ConfigurationException {
this.cfg = cfg;
allow = cfg.getAll ("allow");
backlog = cfg.getInt ("backlog", 0);
ignoreISOExceptions = cfg.getBoolean("ignore-iso-exceptions");
String ip = cfg.get ("bind-address", null);
if (ip != null) {
try {
bindAddr = InetAddress.getByName (ip);
} catch (UnknownHostException e) {
throw new ConfigurationException ("Invalid bind-address " + ip, e);
}
}
if (socketFactory == null)
socketFactory = this;
if (socketFactory != this && socketFactory instanceof Configurable) {
((Configurable)socketFactory).setConfiguration (cfg);
}
}
public String getISOChannelNames () {
StringBuilder sb = new StringBuilder ();
Iterator iter = channels.entrySet().iterator();
for (int i=0; iter.hasNext(); i++) {
Map.Entry entry = (Map.Entry) iter.next();
WeakReference ref = (WeakReference) entry.getValue();
ISOChannel c = (ISOChannel) ref.get ();
if (c != null && !LAST.equals (entry.getKey()) && c.isConnected()) {
if (i > 0)
sb.append (' ');
sb.append (entry.getKey());
}
}
return sb.toString();
}
public String getCountersAsString () {
StringBuilder sb = new StringBuilder ();
int cnt[] = getCounters();
sb.append ("connected=");
sb.append (Integer.toString(cnt[0]));
sb.append (", rx=");
sb.append (Integer.toString(cnt[0]));
sb.append (", tx=");
sb.append (Integer.toString(cnt[1]));
sb.append (", last=");
sb.append (lastTxn);
if (lastTxn > 0) {
sb.append (", idle=");
sb.append(System.currentTimeMillis() - lastTxn);
sb.append ("ms");
}
return sb.toString();
}
public int[] getCounters()
{
Iterator iter = channels.entrySet().iterator();
int[] cnt = new int[3];
cnt[2] = 0;
for (int i=0; iter.hasNext(); i++) {
Map.Entry entry = (Map.Entry) iter.next();
WeakReference ref = (WeakReference) entry.getValue();
ISOChannel c = (ISOChannel) ref.get ();
if (c != null && !LAST.equals (entry.getKey()) && c.isConnected()) {
cnt[2]++;
if (c instanceof BaseChannel) {
int[] cc = ((BaseChannel)c).getCounters();
cnt[0] += cc[ISOChannel.RX];
cnt[1] += cc[ISOChannel.TX];
}
}
}
return cnt;
}
public int getTXCounter() {
int cnt[] = getCounters();
return cnt[1];
}
public int getRXCounter() {
int cnt[] = getCounters();
return cnt[0];
}
public int getConnections () {
int cnt[] = getCounters();
return cnt[2];
}
public long getLastTxnTimestampInMillis() {
return lastTxn;
}
public long getIdleTimeInMillis() {
return lastTxn > 0L ? System.currentTimeMillis() - lastTxn : -1L;
}
public String getCountersAsString (String isoChannelName) {
ISOChannel channel = getISOChannel(isoChannelName);
StringBuffer sb = new StringBuffer();
if (channel instanceof BaseChannel) {
int[] counters = ((BaseChannel)channel).getCounters();
append (sb, "rx=", counters[ISOChannel.RX]);
append (sb, ", tx=", counters[ISOChannel.TX]);
append (sb, ", connects=", counters[ISOChannel.CONNECT]);
}
return sb.toString();
}
public void dump (PrintStream p, String indent) {
p.println (indent + getCountersAsString());
Iterator iter = channels.entrySet().iterator();
String inner = indent + " ";
for (int i=0; iter.hasNext(); i++) {
Map.Entry entry = (Map.Entry) iter.next();
WeakReference ref = (WeakReference) entry.getValue();
ISOChannel c = (ISOChannel) ref.get ();
if (c != null && !LAST.equals (entry.getKey()) && c.isConnected()) {
if (c instanceof BaseChannel) {
StringBuilder sb = new StringBuilder ();
int[] cc = ((BaseChannel)c).getCounters();
sb.append (inner);
sb.append (entry.getKey());
sb.append (": rx=");
sb.append (Integer.toString (cc[ISOChannel.RX]));
sb.append (", tx=");
sb.append (Integer.toString (cc[ISOChannel.TX]));
sb.append (", last=");
sb.append (Long.toString(lastTxn));
p.println (sb.toString());
}
}
}
}
private void append (StringBuffer sb, String name, int value) {
sb.append (name);
sb.append (value);
}
}
|
package com.intellij.codeInspection.varScopeCanBeNarrowed;
import com.intellij.codeInsight.daemon.GroupNames;
import com.intellij.codeInspection.InspectionManager;
import com.intellij.codeInspection.LocalQuickFix;
import com.intellij.codeInspection.ProblemDescriptor;
import com.intellij.codeInspection.ProblemHighlightType;
import com.intellij.codeInspection.ex.BaseLocalInspectionTool;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.editor.ScrollType;
import com.intellij.openapi.fileEditor.FileEditorManager;
import com.intellij.openapi.project.Project;
import com.intellij.psi.*;
import com.intellij.psi.codeStyle.CodeStyleManager;
import com.intellij.psi.codeStyle.VariableKind;
import com.intellij.psi.controlFlow.*;
import com.intellij.psi.search.GlobalSearchScope;
import com.intellij.psi.search.LocalSearchScope;
import com.intellij.psi.search.PsiSearchHelper;
import com.intellij.psi.util.PsiTreeUtil;
import com.intellij.psi.util.PsiUtil;
import com.intellij.refactoring.util.RefactoringUtil;
import com.intellij.util.IJSwingUtilities;
import com.intellij.util.IncorrectOperationException;
import com.intellij.util.containers.HashSet;
import java.util.*;
/**
* @author ven
*/
public class FieldCanBeLocalInspection extends BaseLocalInspectionTool {
private static final Logger LOG = Logger.getInstance("#com.intellij.codeInspection.varScopeCanBeNarrowed.FieldCanBeLocalInspection");
public static final String SHORT_NAME = "FieldCanBeLocal";
public String getGroupDisplayName() {
return GroupNames.CLASSLAYOUT_GROUP_NAME;
}
public String getDisplayName() {
return "Field can be local";
}
public String getShortName() {
return SHORT_NAME;
}
public ProblemDescriptor[] checkClass(PsiClass aClass, InspectionManager manager, boolean isOnTheFly) {
PsiManager psiManager = aClass.getManager();
final Set<PsiField> candidates = new LinkedHashSet<PsiField>();
final PsiClass topLevelClass = PsiUtil.getTopLevelClass(aClass);
if (topLevelClass == null) return null;
final PsiField[] fields = aClass.getFields();
NextField:
for (PsiField field : fields) {
if (field.hasModifierProperty(PsiModifier.PRIVATE)) {
final PsiReference[] refs = psiManager.getSearchHelper().findReferences(field, GlobalSearchScope.allScope(psiManager.getProject()),
false);
for (PsiReference ref : refs) {
PsiElement element = ref.getElement();
while (element != null) {
if (element instanceof PsiMethod) {
candidates.add(field);
continue NextField;
}
element = PsiTreeUtil.getParentOfType(element, PsiMember.class);
}
continue NextField;
}
}
}
topLevelClass.accept(new PsiRecursiveElementVisitor() {
public void visitElement(PsiElement element) {
if (candidates.size() > 0) super.visitElement(element);
}
public void visitMethod(PsiMethod method) {
super.visitMethod(method);
final PsiCodeBlock body = method.getBody();
if (body != null) {
try {
final ControlFlow controlFlow = ControlFlowFactory.getControlFlow(body, AllVariablesControlFlowPolicy.getInstance());
final List<PsiReferenceExpression> readBeforeWrite = ControlFlowUtil.getReadBeforeWrite(controlFlow);
for (Iterator<PsiReferenceExpression> iterator = readBeforeWrite.iterator(); iterator.hasNext();) {
final PsiElement resolved = iterator.next().resolve();
if (resolved instanceof PsiField) {
final PsiField field = (PsiField)resolved;
candidates.remove(field);
}
}
}
catch (AnalysisCanceledException e) {
candidates.clear();
}
}
}
});
if (candidates.isEmpty()) return null;
ProblemDescriptor[] result = new ProblemDescriptor[candidates.size()];
int i = 0;
for (Iterator<PsiField> iterator = candidates.iterator(); iterator.hasNext(); i++) {
PsiField field = iterator.next();
final String message = "Field can be converted to one or more local variables.";
result[i] = manager.createProblemDescriptor(field, message, new MyQuickFix(field), ProblemHighlightType.GENERIC_ERROR_OR_WARNING);
}
return result;
}
private static class MyQuickFix implements LocalQuickFix {
private PsiField myField;
public MyQuickFix(final PsiField field) {
myField = field;
}
public String getName() {
return "Convert to local";
}
public void applyFix(Project project, ProblemDescriptor descriptor) {
if (!myField.isValid()) return; //weird. should not get here when field becomes invalid
PsiManager manager = PsiManager.getInstance(project);
PsiSearchHelper helper = manager.getSearchHelper();
Set<PsiMethod> methodSet = new HashSet<PsiMethod>();
final PsiReference[] allRefs = helper.findReferences(myField, GlobalSearchScope.allScope(project), false);
for (PsiReference ref : allRefs) {
if (ref instanceof PsiReferenceExpression) {
final PsiMethod method = PsiTreeUtil.getParentOfType((PsiReferenceExpression)ref, PsiMethod.class);
LOG.assertTrue(method != null);
methodSet.add(method);
}
}
PsiElement newCaretPosition = null;
for (PsiMethod method : methodSet) {
final PsiReference[] refs = helper.findReferences(myField, new LocalSearchScope(method), true);
LOG.assertTrue(refs.length > 0);
Set<PsiReference> refsSet = new HashSet<PsiReference>(Arrays.asList(refs));
PsiCodeBlock anchorBlock = findAnchorBlock(refs);
LOG.assertTrue(anchorBlock != null);
final PsiElementFactory elementFactory = manager.getElementFactory();
final CodeStyleManager styleManager = manager.getCodeStyleManager();
final String propertyName = styleManager.variableNameToPropertyName(myField.getName(), VariableKind.FIELD);
String localName = styleManager.propertyNameToVariableName(propertyName, VariableKind.LOCAL_VARIABLE);
localName = RefactoringUtil.suggestUniqueVariableName(localName, anchorBlock, myField);
try {
final PsiElement anchor = getAnchorElement(anchorBlock, refs);
final PsiElement newDeclaration;
if (anchor instanceof PsiExpressionStatement &&
((PsiExpressionStatement)anchor).getExpression() instanceof PsiAssignmentExpression) {
final PsiAssignmentExpression expression = (PsiAssignmentExpression)((PsiExpressionStatement)anchor).getExpression();
if (expression.getLExpression() instanceof PsiReferenceExpression &&
((PsiReferenceExpression)expression.getLExpression()).isReferenceTo(myField)) {
final PsiExpression initializer = expression.getRExpression();
final PsiDeclarationStatement decl = elementFactory.createVariableDeclarationStatement(localName, myField.getType(), initializer);
newDeclaration = anchor.replace(decl);
refsSet.remove(expression.getLExpression());
retargetReferences(elementFactory, localName, refsSet);
}
else {
newDeclaration = addDeclarationWithoutInitializerAndRetargetReferences(elementFactory, localName, anchorBlock, anchor, refsSet);
}
} else {
newDeclaration = addDeclarationWithoutInitializerAndRetargetReferences(elementFactory, localName, anchorBlock, anchor, refsSet);
}
if (newCaretPosition == null) {
newCaretPosition = newDeclaration;
}
}
catch (IncorrectOperationException e) {
LOG.error(e);
}
}
if (newCaretPosition != null) {
final PsiFile psiFile = myField.getContainingFile();
final Editor editor = FileEditorManager.getInstance(project).getSelectedTextEditor();
if (editor != null && IJSwingUtilities.hasFocus(editor.getComponent())) {
final PsiFile file = PsiDocumentManager.getInstance(project).getPsiFile(editor.getDocument());
if (file == psiFile) {
editor.getCaretModel().moveToOffset(newCaretPosition.getTextOffset());
editor.getScrollingModel().scrollToCaret(ScrollType.RELATIVE);
}
}
}
try {
myField.normalizeDeclaration();
myField.delete();
}
catch (IncorrectOperationException e) {
LOG.error(e);
}
}
private void retargetReferences(final PsiElementFactory elementFactory, final String localName, final Set<PsiReference> refs)
throws IncorrectOperationException {
final PsiReferenceExpression refExpr = (PsiReferenceExpression)elementFactory.createExpressionFromText(localName, null);
for (PsiReference ref : refs) {
if (ref instanceof PsiReferenceExpression) {
((PsiReferenceExpression)ref).replace(refExpr);
}
}
}
private PsiElement addDeclarationWithoutInitializerAndRetargetReferences(final PsiElementFactory elementFactory,
final String localName,
final PsiCodeBlock anchorBlock, final PsiElement anchor,
final Set<PsiReference> refs)
throws IncorrectOperationException {
final PsiElement newDeclaration;
final PsiDeclarationStatement decl = elementFactory.createVariableDeclarationStatement(localName, myField.getType(), null);
newDeclaration = anchorBlock.addBefore(decl, anchor);
retargetReferences(elementFactory, localName, refs);
return newDeclaration;
}
public String getFamilyName() {
return getName();
}
private static PsiElement getAnchorElement(final PsiCodeBlock anchorBlock, final PsiReference[] refs) {
PsiElement firstElement = null;
for (PsiReference reference : refs) {
final PsiElement element = reference.getElement();
if (firstElement == null || firstElement.getTextRange().getStartOffset() > element.getTextRange().getStartOffset()) {
firstElement = element;
}
}
LOG.assertTrue(firstElement != null);
while (firstElement.getParent() != anchorBlock) {
firstElement = firstElement.getParent();
}
return firstElement;
}
private static PsiCodeBlock findAnchorBlock(final PsiReference[] refs) {
PsiCodeBlock result = null;
for (PsiReference psiReference : refs) {
final PsiElement element = psiReference.getElement();
PsiCodeBlock block = PsiTreeUtil.getParentOfType(element, PsiCodeBlock.class);
if (result == null) {
result = block;
}
else {
final PsiElement commonParent = PsiTreeUtil.findCommonParent(result, block);
result = PsiTreeUtil.getParentOfType(commonParent, PsiCodeBlock.class, false);
}
}
return result;
}
}
}
|
package ca.bc.gov.restrictions;
import java.security.Principal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.nuxeo.ecm.core.api.security.ACE;
import org.nuxeo.ecm.core.api.security.ACL;
import org.nuxeo.ecm.core.api.security.ACP;
import org.nuxeo.ecm.core.api.security.Access;
import org.nuxeo.ecm.core.api.security.SecurityConstants;
import org.nuxeo.ecm.core.model.Document;
import org.nuxeo.ecm.core.security.AbstractSecurityPolicy;
import ca.bc.gov.utils.CustomSecurityConstants;
/**
* Language recorders policies
*/
public class LanguageRecorders extends AbstractSecurityPolicy {
private static ArrayList<String> allowedDocumentTypes = new ArrayList<String>();
private Boolean hasPermissionInACP(ACP mergedAcp, List<String> additionalPrincipalsList, String permission) {
for (ACL acl : mergedAcp.getACLs()) {
for (ACE ace : acl.getACEs()) {
if (ace.isGranted() && additionalPrincipalsList.contains(ace.getUsername()) && ace.getPermission().equals(permission) ) {
return true;
}
}
}
return false;
}
@Override
public boolean isRestrictingPermission(String permission) {
if ( permission.equals(SecurityConstants.ADD_CHILDREN) ||
permission.equals(SecurityConstants.WRITE) ||
permission.equals(SecurityConstants.WRITE_PROPERTIES) ||
permission.equals(CustomSecurityConstants.CAN_ASK_FOR_PUBLISH) ||
permission.equals(SecurityConstants.REMOVE_CHILDREN) ||
permission.equals(SecurityConstants.REMOVE)) {
return true;
}
return false;
}
@Override
public Access checkPermission(Document doc, ACP mergedAcp,
Principal principal, String permission,
String[] resolvedPermissions, String[] additionalPrincipals) throws SecurityException {
List<String> resolvedPermissionsList = Arrays.asList(resolvedPermissions);
List<String> additionalPrincipalsList = Arrays.asList(additionalPrincipals);
// Skip administrators and system
if (additionalPrincipalsList.contains("administrators") || principal.equals("system")) {
return Access.UNKNOWN;
}
if ("BROWSE".equals(permission)) {
return Access.UNKNOWN;
}
String docType = doc.getType().getName();
String docTypeParent = null;
if (doc.getParent() != null) {
docTypeParent = doc.getParent().getType().getName();
}
if ( hasPermissionInACP(mergedAcp, additionalPrincipalsList, CustomSecurityConstants.RECORD) ) {
if (allowedDocumentTypes.isEmpty()) {
allowedDocumentTypes.add("FVCategories");
allowedDocumentTypes.add("FVContributors");
allowedDocumentTypes.add("FVDictionary");
allowedDocumentTypes.add("FVResources");
}
// Allow adding children and removing children on allowed types
if (allowedDocumentTypes.contains(docType) && (resolvedPermissionsList.contains(SecurityConstants.ADD_CHILDREN) || resolvedPermissionsList.contains(SecurityConstants.REMOVE_CHILDREN)) ) {
return Access.GRANT;
}
// Allow Publishing, Writing and Removing on allowed document type children
if (docTypeParent != null && allowedDocumentTypes.contains(docTypeParent) && (resolvedPermissionsList.contains(SecurityConstants.WRITE_PROPERTIES) || resolvedPermissionsList.contains(SecurityConstants.REMOVE) || resolvedPermissionsList.contains(SecurityConstants.WRITE)) ) {
return Access.GRANT;
}
}
// Recorders can only publish to their allowed types (OK to use groups as this is globally applicable)
if (additionalPrincipalsList.contains(CustomSecurityConstants.RECORDERS_GROUP) || additionalPrincipalsList.contains(CustomSecurityConstants.RECORDERS_APPROVERS_GROUP)) {
if (!allowedDocumentTypes.contains(docType) && (resolvedPermissionsList.contains(CustomSecurityConstants.CAN_ASK_FOR_PUBLISH)) ) {
return Access.DENY;
}
}
return Access.UNKNOWN;
}
@Override
public boolean isExpressibleInQuery(String repositoryName) {
return false;
}
}
|
package org.xwiki.tool.spoon;
import java.util.List;
import java.util.Map;
import org.apache.log4j.Level;
import spoon.processing.AbstractProcessor;
import spoon.processing.Property;
import spoon.reflect.code.CtExpression;
import spoon.reflect.code.CtInvocation;
/**
* Failed the build if some code is calling a forbidden method.
*
* @version $Id$
* @since 9.9RC2
*/
public class ForbiddenInvocationProcessor extends AbstractProcessor<CtInvocation<?>>
{
@Property
private Map<String, List<String>> methods;
@Override
public void process(CtInvocation<?> element)
{
CtExpression<?> target = element.getTarget();
if (target != null && target.getType() != null) {
String type = target.getType().getQualifiedName();
List<String> methodList = this.methods.get(type);
if (methodList != null) {
String method = element.getExecutable().getSimpleName();
if (methodList.contains(method)) {
getFactory().getEnvironment().report(this, Level.ERROR, element,
"Forbidden call to " + type + "#" + method);
// Forcing the build to stop
throw new RuntimeException("Forbidden call to " + type + "#" + method);
}
}
}
}
}
|
package org.xwiki.test.ui.framework;
import org.openqa.selenium.By;
import org.openqa.selenium.NoSuchElementException;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.events.EventFiringWebDriver;
import org.xwiki.test.integration.XWikiExecutor;
/**
* This is a container for holding all of the information which should persist throughout all of the tests.
*
* @version $Id$
* @since 2.4M1
*/
public class PersistentTestContext
{
/** This starts and stops the wiki engine. */
private final XWikiExecutor executor;
private final WebDriver driver;
/** Utility methods which should be available to tests and to pages. */
private final TestUtils util = new TestUtils();
public PersistentTestContext() throws Exception
{
this.executor = new XWikiExecutor(0);
executor.start();
// Ensure that we display page source information if an HTML fails to be found, for easier debugging.
this.driver = new EventFiringWebDriver(new FirefoxDriver()) {
@Override public WebElement findElement(By by)
{
try {
return super.findElement(by);
} catch (NoSuchElementException e) {
throw new NoSuchElementException(e.getMessage() + " Page source [" + getPageSource()
+ "]", e.getCause());
}
}
};
}
public PersistentTestContext(PersistentTestContext toClone)
{
this.executor = toClone.executor;
this.driver = toClone.driver;
}
public WebDriver getDriver()
{
return this.driver;
}
/**
* @return Utility class with functions not specific to any test or element.
*/
public TestUtils getUtil()
{
return this.util;
}
public void shutdown() throws Exception
{
driver.close();
executor.stop();
}
/**
* Get a clone of this context which cannot be stopped by calling shutdown. this is needed so that individual tests
* don't shutdown when AllTests ware being run.
*/
public PersistentTestContext getUnstoppable()
{
return new PersistentTestContext(this)
{
public void shutdown()
{
// Do nothing, that's why it's unstoppable.
}
};
}
}
|
package io.github.lonamiwebs.stringlate.git;
import android.app.Activity;
import org.eclipse.jgit.lib.ProgressMonitor;
import io.github.lonamiwebs.stringlate.R;
import io.github.lonamiwebs.stringlate.interfaces.ProgressUpdateCallback;
public abstract class GitCloneProgressCallback
implements ProgressUpdateCallback, ProgressMonitor {
private Activity mActivity;
private int mCurrentTask, mDone, mWork;
private long mLastMs;
private final static long DELAY_PER_UPDATE = 60; // 60ms
protected GitCloneProgressCallback(Activity activity) {
mActivity = activity;
}
@Override
final public void beginTask(String title, int totalWork) {
mCurrentTask++;
mLastMs = 0;
mDone = 0;
mWork = totalWork;
}
@Override
final public void update(int completed) {
mDone += completed;
// This method is called way so often, slow it down
long time = System.currentTimeMillis();
if (time - mLastMs >= DELAY_PER_UPDATE) {
mLastMs = time;
updateProgress();
}
}
@Override
final public void start(int totalTasks) { /* Total tasks is a liar */ }
@Override
final public void endTask() { }
private void updateProgress() {
final String title = mActivity.getString(R.string.cloning_repo);
final String content = mActivity.getString(
R.string.cloning_repo_progress, getProgress(mCurrentTask, mDone, mWork));
// TODO This probably can be improved. Some handler to post the result?
mActivity.runOnUiThread(new Runnable() {
@Override
public void run() {
onProgressUpdate(title, content);
}
});
}
private static float getProgress(int task, float done, float work) {
// After timing cloning a large repository (F-Droid client) twice and averaging:
if (work > 0 && task < 5) {
return getTotalTime(task) + (done / work) * getTime(task);
} else {
return getTotalTime(task);
}
}
private static float getTime(int task) {
switch (task) {
case 1: return 0.003f;
case 2: return 0.204f;
case 3: return 45.74f;
case 4: return 54.52f;
default: return 0.00f;
}
}
private static float getTotalTime(int untilTask) {
switch (untilTask) {
case 1: return 0.000f;
case 2: return 0.003f;
case 3: return 0.207f;
case 4: return 45.95f;
default: return 1.00f;
}
}
@Override
final public boolean isCancelled() {
return false;
}
}
|
package be.kuleuven.cs.distrinet.jnome.core.expression.invocation;
import static be.kuleuven.cs.distrinet.rejuse.collection.CollectionOperations.exists;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import org.aikodi.chameleon.core.lookup.LookupException;
import org.aikodi.chameleon.oo.language.ObjectOrientedLanguage;
import org.aikodi.chameleon.oo.type.Type;
import org.aikodi.chameleon.oo.type.TypeInstantiation;
import org.aikodi.chameleon.oo.type.generics.CapturedTypeParameter;
import org.aikodi.chameleon.oo.type.generics.EqualityConstraint;
import org.aikodi.chameleon.oo.type.generics.EqualityTypeArgument;
import org.aikodi.chameleon.oo.type.generics.ExtendsWildcard;
import org.aikodi.chameleon.oo.type.generics.InstantiatedTypeParameter;
import org.aikodi.chameleon.oo.type.generics.SuperWildcard;
import org.aikodi.chameleon.oo.type.generics.TypeArgument;
import org.aikodi.chameleon.oo.type.generics.TypeArgumentWithTypeReference;
import org.aikodi.chameleon.oo.type.generics.TypeConstraint;
import org.aikodi.chameleon.oo.type.generics.TypeParameter;
import org.aikodi.chameleon.oo.type.generics.TypeVariable;
import org.aikodi.chameleon.util.Util;
import org.aikodi.chameleon.workspace.View;
import be.kuleuven.cs.distrinet.jnome.core.language.Java7;
import be.kuleuven.cs.distrinet.jnome.core.type.ArrayType;
import be.kuleuven.cs.distrinet.jnome.core.type.ArrayTypeReference;
import be.kuleuven.cs.distrinet.jnome.core.type.BasicJavaTypeReference;
import be.kuleuven.cs.distrinet.jnome.core.type.JavaTypeReference;
import be.kuleuven.cs.distrinet.rejuse.logic.ternary.Ternary;
import be.kuleuven.cs.distrinet.rejuse.predicate.Predicate;
/**
* A = type()
* F = typeReference()
*
* @author Marko van Dooren
*/
public abstract class FirstPhaseConstraint extends Constraint<FirstPhaseConstraint, FirstPhaseConstraintSet> {
/**
*
* @param type
* @param tref
*/
public FirstPhaseConstraint(JavaTypeReference A, Type F) {
_A = A;
_F = F;
}
private JavaTypeReference _A;
public Type A() throws LookupException {
return _A.getElement();
}
public JavaTypeReference ARef() {
return _A;
}
// private JavaTypeReference _typeReference;
// public JavaTypeReference typeReference() {
// return _typeReference;
public Type F() {
return _F;
}
private Type _F;
public List<SecondPhaseConstraint> process() throws LookupException {
List<SecondPhaseConstraint> result = new ArrayList<SecondPhaseConstraint>();
// If A is the type of null, no constraint is implied on Tj.
Type A = A();
View view = A.view();
ObjectOrientedLanguage l = view.language(ObjectOrientedLanguage.class);
if(! A.equals(l.getNullType(view.namespace()))) {
result.addAll(processFirstLevel());
}
return result;
}
public List<SecondPhaseConstraint> processFirstLevel() throws LookupException {
List<SecondPhaseConstraint> result = new ArrayList<SecondPhaseConstraint>();
// Declaration declarator = typeReference().getDeclarator();
if(F() instanceof TypeVariable && parent().typeParameters().contains(((TypeVariable)F()).parameter())) {
// Otherwise, if F=Tj, then the constraint Tj :> A is implied.
result.add(FequalsTj(((TypeVariable)F()).parameter(), ARef()));
}
else if(F() instanceof ArrayType) {
// If F=U[], where the type U involves Tj, then if A is an array type V[], or
// a type variable with an upper bound that is an array type V[], where V is a
// reference type, this algorithm is applied recursively to the constraint V<<U
if(A() instanceof ArrayType && involvesTypeParameter(F())) {
Type componentType = ((ArrayType)A()).elementType();
if(componentType.is(language().REFERENCE_TYPE) == Ternary.TRUE) {
JavaTypeReference componentTypeReference = ((ArrayTypeReference)Util.clone(ARef())).elementTypeReference();
componentTypeReference.setUniParent(ARef().parent());
FirstPhaseConstraint recursive = Array(componentTypeReference, ((ArrayType)F()).elementType());
result.addAll(recursive.process());
// FIXME: can't we unwrap the entire array dimension at once? This seems rather inefficient.
}
}
} else if(A().is(language().PRIMITIVE_TYPE) != Ternary.TRUE){
// i is the index of the parameter we are processing.
// V= the type reference of the i-th type parameter of some supertype G of A.
List<TypeArgument> actualsOfF = new ArrayList<TypeArgument>();
for(TypeParameter par: F().parameters(TypeParameter.class)) {
if(par instanceof InstantiatedTypeParameter) {
actualsOfF.add(((InstantiatedTypeParameter)par).argument());
}
else if(par instanceof CapturedTypeParameter) {
List<TypeConstraint> constraints = ((CapturedTypeParameter) par).constraints();
if(constraints.size() == 1 && constraints.get(0) instanceof EqualityConstraint) {
EqualityConstraint eq = (EqualityConstraint) constraints.get(0);
EqualityTypeArgument arg = language().createEqualityTypeArgument(Util.clone(eq.typeReference()));
arg.setUniParent(eq);
actualsOfF.add(arg);
}
}
}
int i = 0;
for(TypeArgument typeArgumentOfFormalParameter: actualsOfF) {
if(typeArgumentOfFormalParameter instanceof EqualityTypeArgument) {
JavaTypeReference U = (JavaTypeReference) ((EqualityTypeArgument)typeArgumentOfFormalParameter).typeReference();
if(involvesTypeParameter(U)) {
caseSSFormalBasic(result, U, i);
}
} else if(typeArgumentOfFormalParameter instanceof ExtendsWildcard) {
JavaTypeReference U = (JavaTypeReference) ((ExtendsWildcard)typeArgumentOfFormalParameter).typeReference();
if(involvesTypeParameter(U)) {
caseSSFormalExtends(result, U, i);
}
} else if(typeArgumentOfFormalParameter instanceof SuperWildcard) {
JavaTypeReference U = (JavaTypeReference) ((SuperWildcard)typeArgumentOfFormalParameter).typeReference();
if(involvesTypeParameter(U)) {
caseSSFormalSuper(result, U, i);
}
}
i++;
}
}
// else {
// result.addAll(processSpecifics());
return result;
}
public abstract void caseSSFormalBasic(List<SecondPhaseConstraint> result, JavaTypeReference U,
int index) throws LookupException;
public abstract void caseSSFormalExtends(List<SecondPhaseConstraint> result, JavaTypeReference U,
int index) throws LookupException;
public abstract void caseSSFormalSuper(List<SecondPhaseConstraint> result, JavaTypeReference U,
int index) throws LookupException;
public abstract SecondPhaseConstraint FequalsTj(TypeParameter declarator, JavaTypeReference type);
public abstract FirstPhaseConstraint Array(JavaTypeReference componentType, Type componentTypeReference);
// public abstract List<SecondPhaseConstraint> processSpecifics() throws LookupException;
public boolean involvesTypeParameter(JavaTypeReference tref) throws LookupException {
return ! involvedTypeParameters(tref).isEmpty();
}
public boolean involvesTypeParameter(Type type) throws LookupException {
return ((type instanceof TypeVariable) && (parent().typeParameters().contains(((TypeVariable) type).parameter())))
|| ((type instanceof ArrayType) && (involvesTypeParameter(((ArrayType) type).elementType())))
|| ((type instanceof TypeInstantiation) && (involvesTypeParameter(type.baseType())))
|| exists(type.parameters(TypeParameter.class), object -> (object instanceof InstantiatedTypeParameter)
&& involvesTypeParameter(((InstantiatedTypeParameter) object).argument()));
}
public boolean involvesTypeParameter(TypeArgument arg) throws LookupException {
return (arg instanceof TypeArgumentWithTypeReference) &&
involvesTypeParameter((JavaTypeReference) ((TypeArgumentWithTypeReference)arg).typeReference());
}
public List<TypeParameter> involvedTypeParameters(JavaTypeReference tref) throws LookupException {
Predicate<BasicJavaTypeReference, LookupException> predicate =
object -> parent().typeParameters().contains(object.getDeclarator());
List<BasicJavaTypeReference> list = tref.descendants(BasicJavaTypeReference.class, predicate);
if((tref instanceof BasicJavaTypeReference) && predicate.eval((BasicJavaTypeReference) tref)) {
list.add((BasicJavaTypeReference) tref);
}
List<TypeParameter> parameters = new ArrayList<TypeParameter>();
for(BasicJavaTypeReference cref: list) {
parameters.add((TypeParameter) cref.getDeclarator());
}
return parameters;
}
public Java7 language() throws LookupException {
return A().language(Java7.class);
}
public View view() throws LookupException {
return A().view();
}
protected Type typeWithSameBaseTypeAs(Type example, Collection<Type> toBeSearched) {
Type baseType = example.baseType();
for(Type type:toBeSearched) {
if(type.baseType().equals(baseType)) {
return type;
}
}
return null;
}
}
|
package org.rstudio.studio.client.workbench.prefs.views;
import com.google.gwt.resources.client.ImageResource;
import com.google.gwt.user.client.ui.CheckBox;
import com.google.inject.Inject;
import org.rstudio.core.client.prefs.PreferencesDialogBaseResources;
import org.rstudio.core.client.widget.NumericValueWidget;
import org.rstudio.studio.client.workbench.prefs.model.RPrefs;
import org.rstudio.studio.client.workbench.prefs.model.UIPrefs;
public class EditingPreferencesPane extends PreferencesPane
{
@Inject
public EditingPreferencesPane(UIPrefs prefs)
{
prefs_ = prefs;
add(checkboxPref("Highlight selected word", prefs.highlightSelectedWord()));
add(checkboxPref("Highlight selected line", prefs.highlightSelectedLine()));
add(checkboxPref("Show line numbers", prefs.showLineNumbers()));
add(tight(spacesForTab_ = checkboxPref("Insert spaces for tab", prefs.useSpacesForTab())));
add(indent(tabWidth_ = numericPref("Tab width", prefs.numSpacesForTab())));
add(tight(showMargin_ = checkboxPref("Show margin", prefs.showMargin())));
add(indent(marginCol_ = numericPref("Margin column", prefs.printMarginColumn())));
add(checkboxPref("Show whitespace characters", prefs_.showInvisibles()));
add(checkboxPref("Show indent guides", prefs_.showIndentGuides()));
add(checkboxPref("Blinking cursor", prefs_.blinkingCursor()));
add(checkboxPref("Insert matching parens/quotes", prefs_.insertMatching()));
add(checkboxPref("Auto-indent code after paste", prefs_.reindentOnPaste()));
add(checkboxPref("Vertically align arguments in auto-indent", prefs_.verticallyAlignArgumentIndent()));
add(checkboxPref("Soft-wrap R source files", prefs_.softWrapRFiles()));
add(checkboxPref("Focus console after executing from source", prefs_.focusConsoleAfterExec()));
add(checkboxPref("Show syntax highlighting in console input", prefs_.syntaxColorConsole()));
add(checkboxPref("Enable vim editing mode", prefs_.useVimMode()));
}
@Override
public ImageResource getIcon()
{
return PreferencesDialogBaseResources.INSTANCE.iconCodeEditing();
}
@Override
public boolean validate()
{
return (!spacesForTab_.getValue() || tabWidth_.validatePositive("Tab width")) &&
(!showMargin_.getValue() || marginCol_.validate("Margin column"));
}
@Override
public String getName()
{
return "Code Editing";
}
@Override
protected void initialize(RPrefs prefs)
{
}
private final UIPrefs prefs_;
private final NumericValueWidget tabWidth_;
private final NumericValueWidget marginCol_;
private final CheckBox spacesForTab_;
private final CheckBox showMargin_;
}
|
package org.activiti.cycle.impl.connector.signavio.transform.pattern;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.activiti.cycle.RepositoryConnector;
import org.activiti.cycle.impl.connector.signavio.SignavioPluginDefinition;
import org.activiti.cycle.impl.connector.signavio.transform.JsonTransformationException;
import org.oryxeditor.server.diagram.Diagram;
import org.oryxeditor.server.diagram.DiagramBuilder;
import org.oryxeditor.server.diagram.Shape;
import org.oryxeditor.server.diagram.StencilType;
/**
* @author Falko Menge
*/
public class SubProcessExpansion extends OryxTransformation {
public static final String STENCIL_SUBPROCESS = "Subprocess";
public static final String STENCIL_COLLAPSED_SUBPROCESS = "CollapsedSubprocess";
public static final String PROPERTY_NAME = "name";
public static final String PROPERTY_ENTRY = "entry";
public static final String PROPERTY_IS_CALL_ACTIVITY = "callacitivity";
private RepositoryConnector connector;
public SubProcessExpansion(RepositoryConnector repositoryConnector) {
this.connector = repositoryConnector;
}
@Override
public Diagram transform(Diagram diagram) {
expandSubProcesses(diagram);
return diagram;
}
private void expandSubProcesses(Diagram diagram) {
List<Shape> shapes = diagram.getShapes();
for (Shape shape : shapes) {
if (STENCIL_COLLAPSED_SUBPROCESS.equals(shape.getStencilId()) && !"true".equals(shape.getProperty(PROPERTY_IS_CALL_ACTIVITY))) {
String subProcessUrl = shape.getProperty(PROPERTY_ENTRY);
if (subProcessUrl != null && subProcessUrl.length() > 0) {
String subProcessName = shape.getProperty(PROPERTY_NAME);
try {
String subProcessId = getModelIdFromSignavioUrl(subProcessUrl);
String representationName = SignavioPluginDefinition.CONTENT_REPRESENTATION_ID_JSON;
String subProcessJson = connector.getContent(subProcessId, representationName).asString();
Diagram subProcess = DiagramBuilder.parseJson(subProcessJson);
// FIXME subProcess = new ExtractProcessOfParticipant("Process Engine").transform(subProcess);
expandSubProcesses(subProcess);
shape.setStencil(new StencilType(STENCIL_SUBPROCESS));
ArrayList<Shape> childShapes = shape.getChildShapes();
childShapes.addAll(subProcess.getChildShapes());
} catch (Exception e) {
throw new JsonTransformationException(
"Error while retrieving Sub-Process"
+ " '" + subProcessName + "'"
+ " (URL: " + subProcessUrl + ").",
e);
}
}
}
}
}
public static String getModelIdFromSignavioUrl(String subProcessUrl) throws UnsupportedEncodingException {
String modelId = null;
List<Pattern> patterns = new ArrayList<Pattern>();
patterns.add(Pattern.compile("^.*/p/model/(.*)$"));
patterns.add(Pattern.compile("^.*/p/editor[?]id=(.*)$")); // workaround for Activiti Modeler
for (Pattern pattern : patterns) {
Matcher matcher = pattern.matcher(subProcessUrl);
if (matcher.matches()) {
modelId = URLDecoder.decode(matcher.group(1), "UTF-8");
break;
}
}
return modelId;
}
}
|
package org.openhab.binding.zwave.internal;
import java.math.BigDecimal;
import java.net.URI;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import org.eclipse.smarthome.config.core.ConfigDescription;
import org.eclipse.smarthome.config.core.ConfigDescriptionParameter;
import org.eclipse.smarthome.config.core.ConfigDescriptionParameter.Type;
import org.eclipse.smarthome.config.core.ConfigDescriptionParameterBuilder;
import org.eclipse.smarthome.config.core.ConfigDescriptionParameterGroup;
import org.eclipse.smarthome.config.core.ConfigDescriptionProvider;
import org.eclipse.smarthome.config.core.ConfigDescriptionRegistry;
import org.eclipse.smarthome.config.core.ConfigOptionProvider;
import org.eclipse.smarthome.config.core.ParameterOption;
import org.eclipse.smarthome.core.thing.Thing;
import org.eclipse.smarthome.core.thing.ThingRegistry;
import org.eclipse.smarthome.core.thing.ThingTypeUID;
import org.eclipse.smarthome.core.thing.ThingUID;
import org.eclipse.smarthome.core.thing.type.ThingType;
import org.eclipse.smarthome.core.thing.type.ThingTypeRegistry;
import org.openhab.binding.zwave.ZWaveBindingConstants;
import org.openhab.binding.zwave.handler.ZWaveControllerHandler;
import org.openhab.binding.zwave.internal.protocol.ZWaveNode;
import org.openhab.binding.zwave.internal.protocol.commandclass.ZWaveCommandClass;
import org.openhab.binding.zwave.internal.protocol.commandclass.ZWaveCommandClass.CommandClass;
import org.openhab.binding.zwave.internal.protocol.commandclass.ZWaveUserCodeCommandClass;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.collect.ImmutableSet;
public class ZWaveConfigProvider implements ConfigDescriptionProvider, ConfigOptionProvider {
private final Logger logger = LoggerFactory.getLogger(ZWaveConfigProvider.class);
private static ThingRegistry thingRegistry;
private static ThingTypeRegistry thingTypeRegistry;
private static ConfigDescriptionRegistry configDescriptionRegistry;
private static Set<ThingTypeUID> zwaveThingTypeUIDList = new HashSet<ThingTypeUID>();
private static List<ZWaveProduct> productIndex = new ArrayList<ZWaveProduct>();
private static final Object productIndexLock = new Object();
// The following is a list of classes that are controllable.
// This is used to filter endpoints so that when we display a list of nodes/endpoints
// for configuring associations, we only list endpoints that are useful
private static final Set<ZWaveCommandClass.CommandClass> controllableClasses = ImmutableSet.of(CommandClass.BASIC,
CommandClass.SWITCH_BINARY, CommandClass.SWITCH_MULTILEVEL, CommandClass.SWITCH_TOGGLE_BINARY,
CommandClass.SWITCH_TOGGLE_MULTILEVEL, CommandClass.CHIMNEY_FAN, CommandClass.THERMOSTAT_HEATING,
CommandClass.THERMOSTAT_MODE, CommandClass.THERMOSTAT_OPERATING_STATE, CommandClass.THERMOSTAT_SETPOINT,
CommandClass.THERMOSTAT_FAN_MODE, CommandClass.THERMOSTAT_FAN_STATE, CommandClass.FIBARO_FGRM_222);
protected void setThingRegistry(ThingRegistry thingRegistry) {
ZWaveConfigProvider.thingRegistry = thingRegistry;
}
protected void unsetThingRegistry(ThingRegistry thingRegistry) {
ZWaveConfigProvider.thingRegistry = null;
}
protected void setThingTypeRegistry(ThingTypeRegistry thingTypeRegistry) {
ZWaveConfigProvider.thingTypeRegistry = thingTypeRegistry;
}
protected void unsetThingTypeRegistry(ThingTypeRegistry thingTypeRegistry) {
ZWaveConfigProvider.thingTypeRegistry = null;
}
protected void setConfigDescriptionRegistry(ConfigDescriptionRegistry configDescriptionRegistry) {
ZWaveConfigProvider.configDescriptionRegistry = configDescriptionRegistry;
}
protected void unsetConfigDescriptionRegistry(ConfigDescriptionRegistry configDescriptionRegistry) {
ZWaveConfigProvider.configDescriptionRegistry = null;
}
@Override
public Collection<ConfigDescription> getConfigDescriptions(Locale locale) {
logger.debug("getConfigDescriptions called");
return Collections.emptySet();
}
@Override
public ConfigDescription getConfigDescription(URI uri, Locale locale) {
if (uri == null) {
return null;
}
if ("thing".equals(uri.getScheme()) == false) {
return null;
}
ThingUID thingUID = new ThingUID(uri.getSchemeSpecificPart());
ThingType thingType = thingTypeRegistry.getThingType(thingUID.getThingTypeUID());
if (thingType == null) {
return null;
}
// Is this a zwave thing?
if (!thingUID.getBindingId().equals(ZWaveBindingConstants.BINDING_ID)) {
return null;
}
// And make sure this is a node because we want to get the id off the end...
if (!thingUID.getId().startsWith("node")) {
return null;
}
int nodeId = Integer.parseInt(thingUID.getId().substring(4));
Thing thing = getThing(thingUID);
if (thing == null) {
return null;
}
ThingUID bridgeUID = thing.getBridgeUID();
// Get the controller for this thing
Thing bridge = getThing(bridgeUID);
if (bridge == null) {
return null;
}
// Get its handler and node
ZWaveControllerHandler handler = (ZWaveControllerHandler) bridge.getHandler();
ZWaveNode node = handler.getNode(nodeId);
List<ConfigDescriptionParameterGroup> groups = new ArrayList<ConfigDescriptionParameterGroup>();
List<ConfigDescriptionParameter> parameters = new ArrayList<ConfigDescriptionParameter>();
groups.add(new ConfigDescriptionParameterGroup("actions", "", false, "Actions", null));
groups.add(new ConfigDescriptionParameterGroup("thingcfg", "home", false, "Device Configuration", null));
parameters.add(ConfigDescriptionParameterBuilder
.create(ZWaveBindingConstants.CONFIGURATION_POLLPERIOD, Type.INTEGER).withLabel("Polling Period")
.withDescription("Set the minimum polling period for this device<BR/>"
+ "Note that the polling period may be longer than set since the binding treats "
+ "polls as the lowest priority data within the network.")
.withDefault("1800").withMinimum(new BigDecimal(15)).withMaximum(new BigDecimal(7200))
.withGroupName("thingcfg").build());
// If we support the wakeup class, then add the configuration
if (node.getCommandClass(ZWaveCommandClass.CommandClass.WAKE_UP) != null) {
groups.add(new ConfigDescriptionParameterGroup("wakeup", "sleep", false, "Wakeup Configuration", null));
parameters.add(ConfigDescriptionParameterBuilder
.create(ZWaveBindingConstants.CONFIGURATION_WAKEUPINTERVAL, Type.TEXT).withLabel("Wakeup Interval")
.withDescription("Sets the number of seconds that the device will wakeup<BR/>"
+ "Setting a shorter time will allow openHAB to configure the device more regularly, but may use more battery power.<BR>"
+ "<B>Note:</B> This setting does not impact device notifications such as alarms.")
.withDefault("").withGroupName("wakeup").build());
parameters.add(
ConfigDescriptionParameterBuilder.create(ZWaveBindingConstants.CONFIGURATION_WAKEUPNODE, Type.TEXT)
.withLabel("Wakeup Node").withAdvanced(true)
.withDescription("Sets the wakeup node to which the device will send notifications.<BR/>"
+ "This should normally be set to the openHAB controller - "
+ "if it isn't, openHAB will not receive notifications when the device wakes up, "
+ "and will not be able to configure the device.")
.withDefault("").withGroupName("wakeup").build());
}
// If we support the node name class, then add the configuration
if (node.getCommandClass(ZWaveCommandClass.CommandClass.NODE_NAMING) != null) {
parameters.add(
ConfigDescriptionParameterBuilder.create(ZWaveBindingConstants.CONFIGURATION_NODENAME, Type.TEXT)
.withLabel("Node Name").withDescription("Sets a string for the device name")
.withGroupName("thingcfg").withDefault("").build());
parameters.add(ConfigDescriptionParameterBuilder
.create(ZWaveBindingConstants.CONFIGURATION_NODELOCATION, Type.TEXT)
.withDescription("Sets a string for the device location").withLabel("Node Location").withDefault("")
.withGroupName("thingcfg").build());
}
// If we support the switch_all class, then add the configuration
if (node.getCommandClass(ZWaveCommandClass.CommandClass.SWITCH_ALL) != null) {
List<ParameterOption> options = new ArrayList<ParameterOption>();
options.add(new ParameterOption("0", "Exclude from All On and All Off groups"));
options.add(new ParameterOption("1", "Include in All On group"));
options.add(new ParameterOption("2", "Include in All Off group"));
options.add(new ParameterOption("255", "Include in All On and All Off groups"));
parameters.add(ConfigDescriptionParameterBuilder
.create(ZWaveBindingConstants.CONFIGURATION_SWITCHALLMODE, Type.TEXT).withLabel("Switch All Mode")
.withDescription("Set the mode for the switch when receiving SWITCH ALL commands.").withDefault("0")
.withGroupName("thingcfg").withOptions(options).build());
}
// If we support the powerlevel class, then add the configuration
if (node.getCommandClass(ZWaveCommandClass.CommandClass.POWERLEVEL) != null) {
List<ParameterOption> options = new ArrayList<ParameterOption>();
options.add(new ParameterOption("0", "Normal"));
options.add(new ParameterOption("1", "Minus 1dB"));
options.add(new ParameterOption("2", "Minus 2dB"));
options.add(new ParameterOption("3", "Minus 3dB"));
options.add(new ParameterOption("4", "Minus 4dB"));
options.add(new ParameterOption("5", "Minus 5dB"));
options.add(new ParameterOption("6", "Minus 6dB"));
options.add(new ParameterOption("7", "Minus 7dB"));
options.add(new ParameterOption("8", "Minus 8dB"));
options.add(new ParameterOption("9", "Minus 9dB"));
parameters.add(ConfigDescriptionParameterBuilder
.create(ZWaveBindingConstants.CONFIGURATION_POWERLEVEL_LEVEL, Type.INTEGER).withLabel("Power Level")
.withDescription(
"Set the RF output level - Normal is maximum power<br>Setting the power to a lower level may be useful to reduce overloading of the receiver in adjacent nodes where they are close together, or if maximum power is not required for battery devices, it may extend battery life by reducing the transmit power.")
.withDefault("0").withGroupName("thingcfg").withOptions(options).build());
parameters.add(ConfigDescriptionParameterBuilder
.create(ZWaveBindingConstants.CONFIGURATION_POWERLEVEL_TIMEOUT, Type.INTEGER)
.withLabel("Power Level Timeout")
.withDescription(
"Set the power level timeout in seconds<br>The node will reset to the normal power level if communications is not made within the specified number of seconds.")
.withDefault("0").withGroupName("thingcfg").withOptions(options).build());
}
// If we support DOOR_LOCK - add options
if (node.getCommandClass(ZWaveCommandClass.CommandClass.DOOR_LOCK) != null) {
parameters.add(ConfigDescriptionParameterBuilder
.create(ZWaveBindingConstants.CONFIGURATION_DOORLOCKTIMEOUT, Type.TEXT).withLabel("Lock Timeout")
.withDescription("Set the timeout on the lock.").withDefault("30").withGroupName("thingcfg")
.build());
}
ZWaveUserCodeCommandClass userCodeClass = (ZWaveUserCodeCommandClass) node
.getCommandClass(ZWaveCommandClass.CommandClass.USER_CODE);
if (userCodeClass != null && userCodeClass.getNumberOfSupportedCodes() > 0) {
groups.add(new ConfigDescriptionParameterGroup("usercode", "lock", false, "User Code", null));
for (int code = 1; code <= userCodeClass.getNumberOfSupportedCodes(); code++) {
parameters.add(ConfigDescriptionParameterBuilder
.create(ZWaveBindingConstants.CONFIGURATION_USERCODE + code, Type.TEXT)
.withLabel("Code " + code).withDescription("Set the user code (4 to 10 numbers)")
.withDefault("").withGroupName("usercode").build());
}
}
List<ParameterOption> options = new ArrayList<ParameterOption>();
options.add(new ParameterOption(ZWaveBindingConstants.ACTION_CHECK_VALUE.toString(), "Do"));
// If we're FAILED, allow removing from the controller
// if (node.getNodeState() == ZWaveNodeState.FAILED) {
parameters.add(ConfigDescriptionParameterBuilder.create("action_remove", Type.INTEGER)
.withLabel("Remove device from controller").withAdvanced(true).withOptions(options)
.withDefault("-232323").withGroupName("actions").build());
// } else {
// Otherwise, allow us to put this on the failed list
parameters.add(ConfigDescriptionParameterBuilder.create("action_failed", Type.INTEGER)
.withLabel("Set device as FAILed").withAdvanced(true).withOptions(options).withDefault("-232323")
.withGroupName("actions").build());
if (node.isInitializationComplete() == true) {
parameters.add(ConfigDescriptionParameterBuilder.create("action_reinit", Type.INTEGER)
.withLabel("Reinitialise the device").withAdvanced(true).withOptions(options).withDefault("-232323")
.withGroupName("actions").build());
}
parameters.add(ConfigDescriptionParameterBuilder.create("action_heal", Type.INTEGER)
.withLabel("Heal the device").withAdvanced(true).withOptions(options).withDefault("-232323")
.withGroupName("actions").build());
return new ConfigDescription(uri, parameters, groups);
}
private static void initialiseZWaveThings() {
// Check that we know about the registry
if (thingTypeRegistry == null) {
return;
}
synchronized (productIndexLock) {
zwaveThingTypeUIDList = new HashSet<ThingTypeUID>();
productIndex = new ArrayList<ZWaveProduct>();
// Get all the thing types
Collection<ThingType> thingTypes = thingTypeRegistry.getThingTypes();
for (ThingType thingType : thingTypes) {
// Is this for our binding?
if (ZWaveBindingConstants.BINDING_ID.equals(thingType.getBindingId()) == false) {
continue;
}
// Create a list of all things supported by this binding
zwaveThingTypeUIDList.add(thingType.getUID());
// Get the properties
Map<String, String> thingProperties = thingType.getProperties();
if (thingProperties.get(ZWaveBindingConstants.PROPERTY_XML_REFERENCES) == null) {
continue;
}
String[] references = thingProperties.get(ZWaveBindingConstants.PROPERTY_XML_REFERENCES).split(",");
for (String ref : references) {
String[] values = ref.split(":");
Integer type;
Integer id = null;
if (values.length != 2) {
continue;
}
type = Integer.parseInt(values[0], 16);
if (!values[1].trim().equals("*")) {
id = Integer.parseInt(values[1], 16);
}
String versionMin = thingProperties.get(ZWaveBindingConstants.PROPERTY_XML_VERSIONMIN);
String versionMax = thingProperties.get(ZWaveBindingConstants.PROPERTY_XML_VERSIONMAX);
productIndex.add(new ZWaveProduct(thingType.getUID(),
Integer.parseInt(thingProperties.get(ZWaveBindingConstants.PROPERTY_XML_MANUFACTURER), 16),
type, id, versionMin, versionMax));
}
}
}
}
public static synchronized List<ZWaveProduct> getProductIndex() {
// if (productIndex.size() == 0) {
initialiseZWaveThings();
return productIndex;
}
public static Set<ThingTypeUID> getSupportedThingTypes() {
// if (zwaveThingTypeUIDList.size() == 0) {
initialiseZWaveThings();
return zwaveThingTypeUIDList;
}
public static ThingType getThingType(ThingTypeUID thingTypeUID) {
// Check that we know about the registry
if (thingTypeRegistry == null) {
return null;
}
return thingTypeRegistry.getThingType(thingTypeUID);
}
public static ThingType getThingType(ZWaveNode node) {
// Check that we know about the registry
if (thingTypeRegistry == null) {
return null;
}
for (ZWaveProduct product : ZWaveConfigProvider.getProductIndex()) {
if (product.match(node) == true) {
return thingTypeRegistry.getThingType(product.thingTypeUID);
}
}
return null;
}
public static ConfigDescription getThingTypeConfig(ThingType type) {
// Check that we know about the registry
if (configDescriptionRegistry == null) {
return null;
}
return configDescriptionRegistry.getConfigDescription(type.getConfigDescriptionURI());
}
public static Thing getThing(ThingUID thingUID) {
// Check that we know about the registry
if (thingRegistry == null) {
return null;
}
return thingRegistry.get(thingUID);
}
/**
* Check if this node supports a controllable command class
*
* @param node the {@link ZWaveNode)
* @return true if a controllable class is supported
*/
private boolean supportsControllableClass(ZWaveNode node) {
for (CommandClass commandClass : controllableClasses) {
if (node.supportsCommandClass(commandClass) == true) {
return true;
}
}
return false;
}
@Override
public Collection<ParameterOption> getParameterOptions(URI uri, String param, Locale locale) {
// We need to update the options of all requests for association groups...
if (!"thing".equals(uri.getScheme())) {
return null;
}
ThingUID thingUID = new ThingUID(uri.getSchemeSpecificPart());
ThingType thingType = thingTypeRegistry.getThingType(thingUID.getThingTypeUID());
if (thingType == null) {
return null;
}
// Is this a zwave thing?
if (!thingUID.getBindingId().equals(ZWaveBindingConstants.BINDING_ID)) {
return null;
}
// And is it an association group?
if (!param.startsWith("group_")) {
return null;
}
// And make sure this is a node because we want to get the id off the end...
if (!thingUID.getId().startsWith("node")) {
return null;
}
int nodeId = Integer.parseInt(thingUID.getId().substring(4));
Thing thing = getThing(thingUID);
ThingUID bridgeUID = thing.getBridgeUID();
// Get the controller for this thing
Thing bridge = getThing(bridgeUID);
if (bridge == null) {
return null;
}
// Get its handler
ZWaveControllerHandler handler = (ZWaveControllerHandler) bridge.getHandler();
boolean supportsMultiInstanceAssociation = false;
ZWaveNode myNode = handler.getNode(nodeId);
if (myNode.getCommandClass(CommandClass.MULTI_INSTANCE_ASSOCIATION) != null) {
supportsMultiInstanceAssociation = true;
}
List<ParameterOption> options = new ArrayList<ParameterOption>();
// Add the controller (ie openHAB) to the top of the list
options.add(new ParameterOption("node_" + handler.getOwnNodeId() + "_0", "openHAB Controller"));
// And iterate over all its nodes
Collection<ZWaveNode> nodes = handler.getNodes();
for (ZWaveNode node : nodes) {
// Don't add its own id or the controller
if (node.getNodeId() == nodeId || node.getNodeId() == handler.getOwnNodeId()) {
continue;
}
// Get this nodes thing so we can find the name
// TODO: Add this when thing names are supported!
// Thing thingNode = getThing(thingUID);
// Add the node for the standard association class if it supports a controllable class
if (supportsControllableClass(node)) {
// TODO: Use the node name
options.add(new ParameterOption("node_" + node.getNodeId() + "_0", "Node " + node.getNodeId()));
}
// If the device supports multi_instance_association class, then add all controllable endpoints as well...
// If this node also supports multi_instance class
if (supportsMultiInstanceAssociation == true && node.getCommandClass(CommandClass.MULTI_INSTANCE) != null) {
// Loop through all the endpoints for this device and add any that are controllable
// for(node.get)
// options.add(new ParameterOption("node" + node.getNodeId() + "." + endpointId, "Node " +
// node.getNodeId()));
}
}
return Collections.unmodifiableList(options);
}
}
|
package au.com.museumvictoria.fieldguide.vic.fork.ui.fragments;
import android.app.Activity;
import android.database.Cursor;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;
import au.com.museumvictoria.fieldguide.vic.fork.R;
import au.com.museumvictoria.fieldguide.vic.fork.adapter.SpeciesListCursorAdapter;
import au.com.museumvictoria.fieldguide.vic.fork.db.FieldGuideDatabase;
/**
* A list of species in a group. This fragment also supports
* tablet devices by allowing list items to be given an 'activated' state upon
* selection. This helps indicate which item is currently being viewed in a
* {@link SpeciesItemDetailFragment}.
*
* <p>Activities containing this fragment MUST implement the {@link Callbacks}
* interface.
*/
public class GroupFragment extends Fragment {
private static final String TAG = GroupFragment.class.getSimpleName();
private static final String ARGUMENT_GROUP_NAME = "speciesgroup";
/**
* Callback interface to be notified when a species is selected. Activities using this fragment
* must implement this interface.
*/
public interface Callback {
void onSpeciesSelected(String speciesId, String name, @Nullable String subname);
}
private Callback callback;
private SimpleAdapter sa;
private ListView mListView;
private Cursor mCursor;
private FieldGuideDatabase fgdb;
/**
* TODO: Document exactly what groupName we expect.
*/
public static GroupFragment newInstance(String groupName) {
Bundle arguments = new Bundle();
arguments.putString(ARGUMENT_GROUP_NAME, groupName);
GroupFragment fragment = new GroupFragment();
fragment.setArguments(arguments);
return fragment;
}
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
callback = (Callback) activity;
} catch (ClassCastException e) {
throw new RuntimeException("Container activity does not implement callback.");
}
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_group, container, false);
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
fgdb = FieldGuideDatabase.getInstance(getActivity()
.getApplicationContext());
mCursor = fgdb.getSpeciesInGroup(getArguments().getString(ARGUMENT_GROUP_NAME),
SpeciesListCursorAdapter.getRequiredColumns());
mListView = (ListView) getView().findViewById(R.id.species_list);
mListView.setFastScrollEnabled(true);
final SpeciesListCursorAdapter adapter =
new SpeciesListCursorAdapter(getActivity().getApplicationContext(), mCursor, 0);
mListView.setAdapter(adapter);
mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Log.i(TAG, "Click" + position + " " + id);
// TODO: Need a better way to get IDs.
callback.onSpeciesSelected(Long.toString(id), adapter.getLabelAtPosition(position),
adapter.getSublabelAtPosition(position));
}
});
}
@Override
public void onDestroy() {
mCursor.close();
super.onDestroy();
}
@Override
public void onDetach() {
callback = null;
super.onDetach();
}
}
|
package com.github.kaiwinter.androidremotenotifications.model;
import com.github.kaiwinter.androidremotenotifications.RemoteNotifications;
import java.util.Date;
/**
* Defines how often the notifications are updated from the server. Doing this on each start of your app ({@link #NOW})
* might lead to too many server calls. You can reduce them by using {@link #WEEKLY} or {@link #MONTHLY}.
*/
public enum UpdatePolicy {
/**
* The update is made now, regardless when the last one was.
*/
NOW(0),
/**
* The update is made once a week. {@link RemoteNotifications} uses an internal shared preference to track when the last update
* was.
*/
WEEKLY(7 * 24 * 60 * 60 * 1000),
/**
* The update is made every second week. {@link RemoteNotifications} uses an internal shared preference to track when the last update
* was.
*/
BI_WEEKLY(WEEKLY.getInterval() * 2),
/**
* The update is made once a month. {@link RemoteNotifications} uses an internal shared preference to track when the last
* update was.
*/
MONTHLY(WEEKLY.getInterval() * 4);
private final long interval;
UpdatePolicy(long interval) {
this.interval = interval;
}
private long getInterval() {
return interval;
}
/**
* Checks if the interval of this {@link UpdatePolicy} is over in regard to the <code>lastUpdate</code>.
*
* @param lastUpdate The {@link Date} of the last update.
* @return <code>true</code> if an update should be done, else <code>false</code>.
*/
public boolean shouldUpdate(Date lastUpdate) {
if (lastUpdate == null) {
return true;
}
// be robust against small time differences when using NOW
return System.currentTimeMillis() - interval >= lastUpdate.getTime();
}
}
|
package edu.pitt.apollo;
import edu.pitt.apollo.db.ApolloDatabaseKeyNotFoundException;
import edu.pitt.apollo.db.ApolloDbUtils;
import edu.pitt.apollo.service.translatorservice.v2_0_1.TranslatorServiceEI;
import edu.pitt.apollo.types.v2_0_1.MethodCallStatusEnum;
import edu.pitt.apollo.types.v2_0_1.RunAndSoftwareIdentification;
import edu.pitt.apollo.types.v2_0_1.RunSimulationMessage;
import edu.pitt.apollo.types.v2_0_1.ServiceRegistrationRecord;
import edu.pitt.apollo.types.v2_0_1.SoftwareIdentification;
import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.sql.SQLException;
import java.util.Map;
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;
import edu.pitt.apollo.service.simulatorservice.v2_0_1.SimulatorServiceEI;
import java.math.BigInteger;
public class ApolloRunSimulationThread extends Thread {
private ApolloDbUtils dbUtils;
private RunSimulationMessage message;
private int runId;
private static ServiceRegistrationRecord translatorServiceRecord;
private ApolloServiceImpl apolloServiceImpl;
public ApolloRunSimulationThread(int runId, RunSimulationMessage message, ApolloDbUtils dbUtils,
ApolloServiceImpl apolloServiceImpl) {
System.out.println("in constructor");
this.message = message;
this.runId = runId;
this.dbUtils = dbUtils;
this.apolloServiceImpl = apolloServiceImpl;
}
@Override
public void run() {
try {
// first call the translator and translate the runSimulationMessage
TranslatorServiceEI translatorPort;
try {
translatorPort = apolloServiceImpl.getTranslatorServicePort(new URL(translatorServiceRecord.getUrl()));
} catch (MalformedURLException ex) {
ErrorUtils.writeErrorToFile("MalformedURLEXception attempting to get the translator port for runId " + runId
+ ". URL was " + translatorServiceRecord.getUrl() + ". Error message was: " + ex.getMessage(),
apolloServiceImpl.getErrorFile(runId));
return;
}
// disable chunking for ZSI
Client client = ClientProxy.getClient(translatorPort);
HTTPConduit http = (HTTPConduit) client.getConduit();
HTTPClientPolicy httpClientPolicy = new HTTPClientPolicy();
httpClientPolicy.setConnectionTimeout(36000);
httpClientPolicy.setAllowChunking(false);
http.setClient(httpClientPolicy);
translatorPort.translateRunSimulationMessage(Integer.toString(runId), message);
// while translator is running, query the status
RunAndSoftwareIdentification translatorRasid = new RunAndSoftwareIdentification();
translatorRasid.setRunId(Integer.toString(runId));
translatorRasid.setSoftwareId(translatorServiceRecord.getSoftwareIdentification());
MethodCallStatusEnum status = MethodCallStatusEnum.QUEUED; // doesn't
// really
// matter
try {
while (!status.equals(MethodCallStatusEnum.TRANSLATION_COMPLETED)) {
Thread.sleep(5000);
status = apolloServiceImpl.getRunStatus(translatorRasid).getStatus();
if (status.equals(MethodCallStatusEnum.FAILED)) {
ErrorUtils.writeErrorToFile("Translator service returned status of FAILED for runId " + runId,
apolloServiceImpl.getErrorFile(runId));
return;
}
}
} catch (InterruptedException ex) {
ErrorUtils.writeErrorToFile("InterruptedException while attempting to get status of translator for runId "
+ runId + ": " + ex.getMessage(), apolloServiceImpl.getErrorFile(runId));
}
// once the translator has finished, call the simulator and start
// the simulation
SoftwareIdentification simulatorIdentification = message.getSimulatorIdentification();
String url = null;
try {
url = dbUtils.getUrlForSoftwareIdentification(simulatorIdentification);
SimulatorServiceEI simulatorPort = apolloServiceImpl.getSimulatorServicePort(new URL(url));
// 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);
simulatorPort.runSimulation(new BigInteger(Integer.toString(runId)), message);
} catch (ApolloDatabaseKeyNotFoundException ex) {
ErrorUtils.writeErrorToFile(
"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(), apolloServiceImpl.getErrorFile(runId));
return;
} catch (ClassNotFoundException ex) {
ErrorUtils.writeErrorToFile(
"ClassNotFoundException attempting to get URL for simulator: "
+ simulatorIdentification.getSoftwareName() + ", version: "
+ simulatorIdentification.getSoftwareVersion() + ", developer: "
+ simulatorIdentification.getSoftwareDeveloper() + " for run id " + runId + ": "
+ ex.getMessage(), apolloServiceImpl.getErrorFile(runId));
return;
} catch (MalformedURLException ex) {
ErrorUtils.writeErrorToFile(
"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(), apolloServiceImpl.getErrorFile(runId));
return;
} catch (SQLException ex) {
ErrorUtils.writeErrorToFile(
"SQLException attempting to get URL for simulator: " + simulatorIdentification.getSoftwareName()
+ ", version: " + simulatorIdentification.getSoftwareVersion() + ", developer: "
+ simulatorIdentification.getSoftwareDeveloper() + " for run id " + runId + ": "
+ ex.getMessage(), apolloServiceImpl.getErrorFile(runId));
return;
}
try {
dbUtils.updateLastServiceToBeCalledForRun(runId, simulatorIdentification);
} catch (ApolloDatabaseKeyNotFoundException ex) {
ErrorUtils.writeErrorToFile("Apollo database key not found attempting to update last service"
+ " call for run id " + runId + ": " + ex.getMessage(), apolloServiceImpl.getErrorFile(runId));
return;
} catch (SQLException ex) {
ErrorUtils.writeErrorToFile("SQLException attempting to update last service" + " call for run id " + runId + ": "
+ ex.getMessage(), apolloServiceImpl.getErrorFile(runId));
return;
} catch (ClassNotFoundException ex) {
ErrorUtils.writeErrorToFile("ClassNotFoundException attempting to update last service" + " call for run id "
+ runId + ": " + ex.getMessage(), apolloServiceImpl.getErrorFile(runId));
return;
}
} catch (IOException e) {
System.out.println("Error writing error file!: " + e.getMessage());
}
}
public static void loadTranslatorSoftwareIdentification() {
System.out.println("Loading translator software identification");
try {
ApolloDbUtils dbUtils = new ApolloDbUtils(new File(ApolloServiceImpl.getDatabasePropertiesFilename()));
Map<Integer, ServiceRegistrationRecord> softwareIdMap = dbUtils.getRegisteredSoftware();
for (Integer id : softwareIdMap.keySet()) {
SoftwareIdentification softwareId = softwareIdMap.get(id).getSoftwareIdentification();
if (softwareId.getSoftwareName().toLowerCase().equals("translator")) {
translatorServiceRecord = softwareIdMap.get(id);
break;
}
}
} catch (ClassNotFoundException ex) {
throw new RuntimeException("ClassNotFoundException attempting to load the translator service record: "
+ ex.getMessage());
} catch (IOException ex) {
throw new RuntimeException("IOException attempting to load the translator service record: " + ex.getMessage());
} catch (SQLException ex) {
throw new RuntimeException("SQLException attempting to load the translator service record: " + ex.getMessage());
}
if (translatorServiceRecord == null) {
throw new RuntimeException("Could not find translator in the list of registered services");
}
}
// static {
// try {
// loadTranslatorSoftwareIdentification();
// } catch (ApolloRunSimulationException ex) {
// throw new
// RuntimeException("ApolloRunSimulationException attempting to load the translator service record: "
// + ex.getMessage());
// } catch (ClassNotFoundException ex) {
// throw new
// RuntimeException("ClassNotFoundException attempting to load the translator service record: "
// + ex.getMessage());
// } catch (IOException ex) {
// throw new
// RuntimeException("IOException attempting to load the translator service record: "
// + ex.getMessage());
// } catch (SQLException ex) {
// throw new
// RuntimeException("SQLException attempting to load the translator service record: "
// + ex.getMessage());
}
|
package com.axelor.apps.production.service.productionorder;
import com.axelor.apps.base.db.Product;
import com.axelor.apps.base.db.repo.SequenceRepository;
import com.axelor.apps.base.service.administration.SequenceService;
import com.axelor.apps.production.db.BillOfMaterial;
import com.axelor.apps.production.db.ManufOrder;
import com.axelor.apps.production.db.ProductionOrder;
import com.axelor.apps.production.db.repo.ProductionOrderRepository;
import com.axelor.apps.production.exceptions.IExceptionMessage;
import com.axelor.apps.production.service.manuforder.ManufOrderService;
import com.axelor.apps.sale.db.SaleOrder;
import com.axelor.exception.AxelorException;
import com.axelor.exception.db.repo.TraceBackRepository;
import com.axelor.i18n.I18n;
import com.google.inject.Inject;
import com.google.inject.persist.Transactional;
import java.lang.invoke.MethodHandles;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class ProductionOrderServiceImpl implements ProductionOrderService {
private final Logger logger = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());
protected ManufOrderService manufOrderService;
protected SequenceService sequenceService;
protected ProductionOrderRepository productionOrderRepo;
@Inject
public ProductionOrderServiceImpl(
ManufOrderService manufOrderService,
SequenceService sequenceService,
ProductionOrderRepository productionOrderRepo) {
this.manufOrderService = manufOrderService;
this.sequenceService = sequenceService;
this.productionOrderRepo = productionOrderRepo;
}
public ProductionOrder createProductionOrder(SaleOrder saleOrder) throws AxelorException {
ProductionOrder productionOrder = new ProductionOrder(this.getProductionOrderSeq());
if (saleOrder != null) {
productionOrder.setClientPartner(saleOrder.getClientPartner());
productionOrder.setSaleOrder(saleOrder);
}
return productionOrder;
}
public String getProductionOrderSeq() throws AxelorException {
String seq = sequenceService.getSequenceNumber(SequenceRepository.PRODUCTION_ORDER);
if (seq == null) {
throw new AxelorException(
TraceBackRepository.CATEGORY_CONFIGURATION_ERROR,
I18n.get(IExceptionMessage.PRODUCTION_ORDER_SEQ));
}
return seq;
}
/**
* Generate a Production Order
*
* @param product Product must be passed in param because product can be different of bill of
* material product (Product variant)
* @param billOfMaterial
* @param qtyRequested
* @param businessProject
* @return
* @throws AxelorException
*/
@Transactional(rollbackOn = {Exception.class})
public ProductionOrder generateProductionOrder(
Product product,
BillOfMaterial billOfMaterial,
BigDecimal qtyRequested,
LocalDateTime startDate)
throws AxelorException {
ProductionOrder productionOrder = this.createProductionOrder(null);
this.addManufOrder(
productionOrder,
product,
billOfMaterial,
qtyRequested,
startDate,
null,
null,
ManufOrderService.ORIGIN_TYPE_OTHER);
return productionOrderRepo.save(productionOrder);
}
@Override
@Transactional(rollbackOn = {Exception.class})
public ProductionOrder addManufOrder(
ProductionOrder productionOrder,
Product product,
BillOfMaterial billOfMaterial,
BigDecimal qtyRequested,
LocalDateTime startDate,
LocalDateTime endDate,
SaleOrder saleOrder,
int originType)
throws AxelorException {
ManufOrder manufOrder =
manufOrderService.generateManufOrder(
product,
qtyRequested,
ManufOrderService.DEFAULT_PRIORITY,
ManufOrderService.IS_TO_INVOICE,
billOfMaterial,
startDate,
endDate,
originType);
if (manufOrder != null) {
if (saleOrder != null) {
manufOrder.addSaleOrderSetItem(saleOrder);
manufOrder.setClientPartner(saleOrder.getClientPartner());
manufOrder.setMoCommentFromSaleOrder(saleOrder.getProductionNote());
}
productionOrder.addManufOrderSetItem(manufOrder);
manufOrder.addProductionOrderSetItem(productionOrder);
}
return productionOrderRepo.save(productionOrder);
}
}
|
package com.grayben.riskExtractor.htmlScorer;
import com.grayben.riskExtractor.htmlScorer.partScorers.Scorer;
import org.jsoup.nodes.Element;
import org.jsoup.nodes.Node;
import org.jsoup.select.NodeVisitor;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
public class ScoringAndFlatteningNodeVisitor implements NodeVisitor {
private Set<Scorer<Element>> elementScorers;
private ScoredText flatText;
public ScoredText getFlatText() {
return flatText;
}
private Map<String, Integer> currentScores;
public Map<String, Integer> getCurrentScores(){
return Collections.unmodifiableMap(currentScores);
}
private String currentString;
private enum Operation {
INCREMENT,
DECREMENT
}
public ScoringAndFlatteningNodeVisitor(Set<Scorer<Element>> elementScorers) {
super();
this.elementScorers = elementScorers;
this.flatText = new ScoredText();
this.currentScores = new HashMap<>();
//initialise currentScores to DEFAULT_SCORE (probably 0)
for (Scorer<Element> scorer: this.elementScorers){
currentScores.put(scorer.getScoreLabel(), scorer.DEFAULT_SCORE);
}
}
@Override
public void head(Node node, int depth) {
validateInput(node, depth);
if(! isElement(node))
return;
Element element = (Element) node;
processElement(element, Operation.INCREMENT);
}
@Override
public void tail(Node node, int depth) {
validateInput(node, depth);
if (! isElement(node))
return;
Element element = (Element) node;
processElement(element, Operation.DECREMENT);
}
private void validateInput(Node node, int depth){
if (node == null)
throw new NullPointerException(
"Node was null"
);
if (depth < 0)
throw new IllegalArgumentException(
"Depth was less than 0"
);
}
private boolean isElement(Node node){
if (node.getClass().equals(Element.class))
return true;
else
return false;
}
private void processElement(Element element, Operation operation){
this.currentString = element.ownText();
updateScores(element, operation);
addScoredTextEntry();
}
private void updateScores(Element element, Operation operation){
for (Scorer<Element> scorer :
elementScorers) {
assert this.currentScores.containsKey(scorer.getScoreLabel());
int currentScore = this.currentScores.get(scorer.getScoreLabel());
int elementScore = scorer.score(element);
int newScore;
switch (operation){
case INCREMENT:
newScore = currentScore + elementScore;
break;
case DECREMENT:
newScore = currentScore - elementScore;
break;
default:
throw new IllegalArgumentException(
"The operation specified is not supported"
);
}
this.currentScores.put(scorer.getScoreLabel(), newScore);
}
}
private void addScoredTextEntry() {
ScoredTextElement textElement = new ScoredTextElement(
this.currentString, this.currentScores
);
this.flatText.add(textElement);
}
}
|
package org.openhealthtools.mdht.uml.cda.core.util;
import java.io.PrintStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.commons.lang.StringUtils;
import org.eclipse.core.resources.IFolder;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.IResourceVisitor;
import org.eclipse.core.resources.IWorkspace;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IExtension;
import org.eclipse.core.runtime.IExtensionPoint;
import org.eclipse.core.runtime.IExtensionRegistry;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.Path;
import org.eclipse.core.runtime.Platform;
import org.eclipse.emf.common.util.EList;
import org.eclipse.emf.common.util.Enumerator;
import org.eclipse.emf.common.util.TreeIterator;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.emf.ecore.util.EcoreUtil;
import org.eclipse.uml2.common.util.UML2Util;
import org.eclipse.uml2.uml.Association;
import org.eclipse.uml2.uml.Class;
import org.eclipse.uml2.uml.Classifier;
import org.eclipse.uml2.uml.Comment;
import org.eclipse.uml2.uml.Constraint;
import org.eclipse.uml2.uml.Element;
import org.eclipse.uml2.uml.Enumeration;
import org.eclipse.uml2.uml.EnumerationLiteral;
import org.eclipse.uml2.uml.Generalization;
import org.eclipse.uml2.uml.NamedElement;
import org.eclipse.uml2.uml.OpaqueExpression;
import org.eclipse.uml2.uml.Package;
import org.eclipse.uml2.uml.Property;
import org.eclipse.uml2.uml.Stereotype;
import org.eclipse.uml2.uml.Type;
import org.eclipse.uml2.uml.ValueSpecification;
import org.eclipse.uml2.uml.util.UMLSwitch;
import org.openhealthtools.mdht.uml.cda.core.profile.EntryRelationship;
import org.openhealthtools.mdht.uml.cda.core.profile.EntryRelationshipKind;
import org.openhealthtools.mdht.uml.cda.core.profile.Inline;
import org.openhealthtools.mdht.uml.cda.core.profile.LogicalConstraint;
import org.openhealthtools.mdht.uml.cda.core.profile.LogicalOperator;
import org.openhealthtools.mdht.uml.cda.core.profile.SeverityKind;
import org.openhealthtools.mdht.uml.cda.core.profile.Validation;
import org.openhealthtools.mdht.uml.common.util.NamedElementUtil;
import org.openhealthtools.mdht.uml.common.util.PropertyList;
import org.openhealthtools.mdht.uml.common.util.UMLUtil;
import org.openhealthtools.mdht.uml.term.core.profile.BindingKind;
import org.openhealthtools.mdht.uml.term.core.profile.CodeSystemConstraint;
import org.openhealthtools.mdht.uml.term.core.profile.CodeSystemVersion;
import org.openhealthtools.mdht.uml.term.core.profile.ValueSetConstraint;
import org.openhealthtools.mdht.uml.term.core.profile.ValueSetVersion;
import org.openhealthtools.mdht.uml.term.core.util.ITermProfileConstants;
import org.openhealthtools.mdht.uml.term.core.util.TermProfileUtil;
public class CDAModelUtil {
public static final String CDA_PACKAGE_NAME = "cda";
public static final String DATATYPES_NS_URI = "http:
/** This base URL may be set from preferences or Ant task options. */
public static String INFOCENTER_URL = "http:
public static final String SEVERITY_ERROR = "ERROR";
public static final String SEVERITY_WARNING = "WARNING";
public static final String SEVERITY_INFO = "INFO";
private static final String EPACKAGE = "Ecore::EPackage";
private static final String EREFERENCE = "Ecore::EReference";
public static final String XMLNAMESPACE = "xmlNamespace";
private static final String NSPREFIX = "nsPrefix";
private static final String NSURI = "nsURI";
// This message may change in the future to specify certain nullFlavor Types (such as the implementation, NI)
private static final String NULLFLAVOR_SECTION_MESSAGE = "If section/@nullFlavor is not present, ";
public static boolean cardinalityAfterElement = false;
public static boolean disablePdfGeneration = false;
public static boolean isAppendConformanceRules = false;
public static Class getCDAClass(Classifier templateClass) {
Class cdaClass = null;
// if the provided class is from CDA and not a template
if (isCDAModel(templateClass) && templateClass instanceof Class) {
return (Class) templateClass;
}
for (Classifier parent : templateClass.allParents()) {
// nearest package may be null if CDA model is not available
if (parent.getNearestPackage() != null) {
if (isCDAModel(parent) && parent instanceof Class) {
cdaClass = (Class) parent;
break;
}
}
}
return cdaClass;
}
public static Property getCDAProperty(Property templateProperty) {
if (templateProperty.getClass_() == null) {
return null;
}
// if the provided property is from a CDA class/datatype and not a template
if (isCDAModel(templateProperty) || isDatatypeModel(templateProperty)) {
return templateProperty;
}
for (Classifier parent : templateProperty.getClass_().allParents()) {
for (Property inherited : parent.getAttributes()) {
if (inherited.getName() != null && inherited.getName().equals(templateProperty.getName()) &&
(isCDAModel(inherited) || isDatatypeModel(inherited))) {
return inherited;
}
}
}
return null;
}
/**
* Returns the nearest inherited property with the same name, or null if not found.
*
* @deprecated Use the {@link UMLUtil#getInheritedProperty(Property)} API, instead.
*/
@Deprecated
public static Property getInheritedProperty(Property templateProperty) {
// for CDA, we restrict to Classes, not other classifiers
if (templateProperty.getClass_() == null) {
return null;
}
return UMLUtil.getInheritedProperty(templateProperty);
}
public static boolean isDatatypeModel(Element element) {
if (element != null && element.getNearestPackage() != null) {
Stereotype ePackage = element.getNearestPackage().getAppliedStereotype("Ecore::EPackage");
if (ePackage != null) {
return DATATYPES_NS_URI.equals(element.getNearestPackage().getValue(ePackage, "nsURI"));
}
}
return false;
}
/**
* isCDAModel - use get top package to support nested uml packages within CDA model
* primarily used for extensions
*
*/
public static boolean isCDAModel(Element element) {
if (element != null) {
Package neareastPackage = element.getNearestPackage();
if (neareastPackage != null) {
Package topPackage = org.openhealthtools.mdht.uml.common.util.UMLUtil.getTopPackage(neareastPackage);
return CDA_PACKAGE_NAME.equals((topPackage != null)
? topPackage.getName()
: "");
}
}
return false;
}
public static Class getCDADatatype(Classifier datatype) {
Class result = null;
// if the provided class is from CDA datatypes
if (isDatatypeModel(datatype) && (datatype instanceof Class)) {
result = (Class) datatype;
} else {
for (Classifier parent : datatype.allParents()) {
// nearest package may be null if CDA datatypes model is not available
if (parent.getNearestPackage() != null) {
if (isDatatypeModel(parent) && (parent instanceof Class)) {
result = (Class) parent;
break;
}
}
}
}
return result;
}
public static boolean isCDAType(Type templateClass, String typeName) {
if (templateClass instanceof Class && typeName != null) {
Class cdaClass = getCDAClass((Class) templateClass);
if (cdaClass != null && typeName.equals(cdaClass.getName())) {
return true;
}
}
return false;
}
public static boolean isClinicalDocument(Type templateClass) {
return isCDAType(templateClass, "ClinicalDocument");
}
public static boolean isSection(Type templateClass) {
return isCDAType(templateClass, "Section");
}
public static boolean isOrganizer(Type templateClass) {
return isCDAType(templateClass, "Organizer");
}
public static boolean isEntry(Type templateClass) {
return isCDAType(templateClass, "Entry");
}
public static boolean isClinicalStatement(Type templateClass) {
if (templateClass instanceof Class) {
Class cdaClass = getCDAClass((Class) templateClass);
String cdaName = cdaClass == null
? null
: cdaClass.getName();
if (cdaClass != null && ("Act".equals(cdaName) || "Encounter".equals(cdaName) ||
"Observation".equals(cdaName) || "ObservationMedia".equals(cdaName) ||
"Organizer".equals(cdaName) || "Procedure".equals(cdaName) || "RegionOfInterest".equals(cdaName) ||
"SubstanceAdministration".equals(cdaName) || "Supply".equals(cdaName))) {
return true;
}
}
return false;
}
public static void composeAllConformanceMessages(Element element, final PrintStream stream, final boolean markup) {
final TreeIterator<EObject> iterator = EcoreUtil.getAllContents(Collections.singletonList(element));
while (iterator != null && iterator.hasNext()) {
EObject child = iterator.next();
UMLSwitch<Object> umlSwitch = new UMLSwitch<Object>() {
@Override
public Object caseAssociation(Association association) {
iterator.prune();
return association;
}
@Override
public Object caseClass(Class umlClass) {
String message = computeConformanceMessage(umlClass, markup);
stream.println(message);
return umlClass;
}
@Override
public Object caseGeneralization(Generalization generalization) {
String message = computeConformanceMessage(generalization, markup);
if (message.length() > 0) {
stream.println(message);
}
return generalization;
}
@Override
public Object caseProperty(Property property) {
String message = computeConformanceMessage(property, markup);
if (message.length() > 0) {
stream.println(message);
}
return property;
}
@Override
public Object caseConstraint(Constraint constraint) {
String message = computeConformanceMessage(constraint, markup);
if (message.length() > 0) {
stream.println(message);
}
return constraint;
}
};
umlSwitch.doSwitch(child);
}
}
public static String getValidationMessage(Element element) {
return getValidationMessage(element, ICDAProfileConstants.VALIDATION);
}
/**
* Obtains the user-specified validation message recorded in the given stereotype, or else
* {@linkplain #computeConformanceMessage(Element, boolean) computes} a suitable conformance message if none.
*
* @param element
* an element on which a validation constraint stereotype is defined
* @param validationStereotypeName
* the stereotype name (may be the abstract {@linkplain ICDAProfileConstants#VALIDATION Validation} stereotype)
*
* @return the most appropriate validation/conformance message
*
* @see #computeConformanceMessage(Element, boolean)
*/
public static String getValidationMessage(Element element, String validationStereotypeName) {
String message = null;
Stereotype validationSupport = CDAProfileUtil.getAppliedCDAStereotype(element, validationStereotypeName);
if (validationSupport != null) {
message = (String) element.getValue(validationSupport, ICDAProfileConstants.VALIDATION_MESSAGE);
}
if (message == null || message.length() == 0) {
message = computeConformanceMessage(element, false);
}
return message;
}
public static String computeConformanceMessage(Element element, final boolean markup) {
UMLSwitch<Object> umlSwitch = new UMLSwitch<Object>() {
@Override
public Object caseAssociation(Association association) {
String message = null;
Property property = getNavigableEnd(association);
if (property != null) {
message = computeConformanceMessage(property, false);
}
return message;
}
@Override
public Object caseClass(Class umlClass) {
return computeConformanceMessage(umlClass, markup);
}
@Override
public Object caseGeneralization(Generalization generalization) {
return computeConformanceMessage(generalization, markup);
}
@Override
public Object caseProperty(Property property) {
return computeConformanceMessage(property, markup);
}
@Override
public Object caseConstraint(Constraint constraint) {
return computeConformanceMessage(constraint, markup);
}
};
return (String) umlSwitch.doSwitch(element);
}
public static String computeConformanceMessage(Class template, final boolean markup) {
String templateId = getTemplateId(template);
String templateVersion = getTemplateVersion(template);
String ruleIds = getConformanceRuleIds(template);
if (templateId == null) {
templateId = "";
}
String templateMultiplicity = CDATemplateComputeBuilder.getMultiplicityRange(getMultiplicityRange(template));
final String templateIdAsBusinessName = "=\"" + templateId + "\"";
final String templateVersionAsBusinessName = "=\"" + templateVersion + "\"";
final String multiplicityRange = templateMultiplicity.isEmpty()
? ""
: " [" + templateMultiplicity + "]";
CDATemplateComputeBuilder cdaTemplater = new CDATemplateComputeBuilder() {
@Override
public String addTemplateIdMultiplicity() {
return multiplicityElementToggle(markup, "templateId", multiplicityRange, "");
}
@Override
public String addRootMultiplicity() {
return multiplicityElementToggle(markup, "@root", " [1..1]", templateIdAsBusinessName);
}
@Override
public String addTemplateVersion() {
return multiplicityElementToggle(markup, "@extension", " [1..1]", templateVersionAsBusinessName);
}
};
return cdaTemplater.setRequireMarkup(markup).setRuleIds(ruleIds).setTemplateVersion(
templateVersion).setMultiplicity(multiplicityRange).compute().toString();
}
public static String computeConformanceMessage(Generalization generalization, boolean markup) {
return computeConformanceMessage(generalization, markup, UMLUtil.getTopPackage(generalization));
}
public static String computeConformanceMessage(Generalization generalization, boolean markup, Package xrefSource) {
Class general = (Class) generalization.getGeneral();
StringBuffer message = new StringBuffer(computeGeneralizationConformanceMessage(general, markup, xrefSource));
appendConformanceRuleIds(generalization, message, markup);
return message.toString();
}
public static String computeGeneralizationConformanceMessage(Class general, boolean markup, Package xrefSource) {
StringBuffer message = new StringBuffer();
String prefix = !UMLUtil.isSameModel(xrefSource, general)
? getModelPrefix(general) + " "
: "";
String xref = computeXref(xrefSource, general);
boolean showXref = markup && (xref != null);
String format = showXref && xref.endsWith(".html")
? "format=\"html\" "
: "";
Class cdaGeneral = getCDAClass(general);
if (cdaGeneral != null) {
message.append(markup
? "<b>"
: "");
message.append("SHALL");
message.append(markup
? "</b>"
: "");
message.append(" conform to ");
} else {
message.append("Extends ");
}
message.append(showXref
? "<xref " + format + "href=\"" + xref + "\">"
: "");
message.append(prefix).append(UMLUtil.splitName(general));
message.append(showXref
? "</xref>"
: "");
String templateId = getTemplateId(general);
String templateVersion = getTemplateVersion(general);
if (templateId != null) {
message.append(" template (templateId: ");
message.append(markup
? "<tt>"
: "");
message.append(templateId);
// if there is an extension, add a colon followed by its value
if (!StringUtils.isEmpty(templateVersion)) {
message.append(":" + templateVersion);
}
message.append(markup
? "</tt>"
: "");
message.append(")");
}
return message.toString();
}
private static String getBusinessName(NamedElement property) {
String businessName = NamedElementUtil.getBusinessName(property);
if (!property.getName().equals(businessName)) {
return (" (" + businessName + ")");
}
return "";
}
private static StringBuffer multiplicityElementToggle(Property property, boolean markup, String elementName) {
StringBuffer message = new StringBuffer();
message.append(
multiplicityElementToggle(markup, elementName, getMultiplicityRange(property), getBusinessName(property)));
return message;
}
private static String multiplicityElementToggle(boolean markup, String elementName, String multiplicityRange,
String businessName) {
StringBuffer message = new StringBuffer();
if (!cardinalityAfterElement) {
message.append(multiplicityRange);
}
message.append(" ");
message.append(markup
? "<tt><b>"
: "");
message.append(elementName);
message.append(markup
? "</b>"
: "");
message.append(businessName);
message.append(markup
? "</tt>"
: "");
if (cardinalityAfterElement) {
message.append(multiplicityRange);
}
return message.toString();
}
public static String computeAssociationConformanceMessage(Property property, boolean markup, Package xrefSource,
boolean appendNestedConformanceRules) {
Class endType = (property.getType() instanceof Class)
? (Class) property.getType()
: null;
if (!isInlineClass(endType) && getTemplateId(property.getClass_()) != null) {
return computeTemplateAssociationConformanceMessage(
property, markup, xrefSource, appendNestedConformanceRules);
}
StringBuffer message = new StringBuffer();
Association association = property.getAssociation();
if (!markup) {
message.append(getPrefixedSplitName(property.getClass_())).append(" ");
}
String keyword = getValidationKeywordWithPropertyRange(association, property);
if (keyword != null) {
message.append(markup
? "<b>"
: "");
message.append(keyword);
message.append(markup
? "</b>"
: "");
message.append(" contain ");
} else {
if (property.getUpper() < 0 || property.getUpper() > 1) {
message.append("contains ");
} else {
message.append("contain ");
}
}
String elementName = getCDAElementName(property);
message.append(getMultiplicityText(property));
message.append(multiplicityElementToggle(property, markup, elementName));
// appendSubsetsNotation(property, message, markup, xrefSource);
if (appendNestedConformanceRules && endType != null) {
if (markup && isInlineClass(endType) && !isPublishSeperately(endType)) {
StringBuilder sb = new StringBuilder();
appendConformanceRuleIds(association, message, markup);
appendPropertyComments(sb, property, markup);
appendConformanceRules(sb, endType, (property.getUpper() == 1
? "This "
: "Such ") +
(property.getUpper() == 1
? elementName
: NameUtilities.pluralize(elementName)) +
" ",
markup);
message.append(" " + sb + " ");
} else {
message.append(", where its type is ");
String prefix = !UMLUtil.isSameModel(xrefSource, endType)
? getModelPrefix(endType) + " "
: "";
String xref = computeXref(xrefSource, endType);
boolean showXref = markup && (xref != null);
String format = showXref && xref.endsWith(".html")
? "format=\"html\" "
: "";
message.append(showXref
? "<xref " + format + "href=\"" + xref + "\">"
: "");
message.append(prefix).append(UMLUtil.splitName(endType));
message.append(showXref
? "</xref>"
: "");
appendConformanceRuleIds(association, message, markup);
}
} else {
appendConformanceRuleIds(association, message, markup);
}
return message.toString();
}
private static String computeTemplateAssociationConformanceMessage(Property property, boolean markup,
Package xrefSource, boolean appendNestedConformanceRules) {
StringBuffer message = new StringBuffer();
Association association = property.getAssociation();
String elementName = getCDAElementName(property);
if (!markup) {
message.append(getPrefixedSplitName(property.getClass_())).append(" ");
}
// errata 384 message support: if the class owner is a section, and it has an association
// to either a clinical statement or an Entry (Act, Observation, etc.), append the message
for (Property p : association.getMemberEnds()) {
if ((p.getName() != null && !p.getName().isEmpty()) && (p.getOwner() != null && p.getType() != null) &&
(isSection((Class) p.getOwner()) && isClinicalStatement(p.getType()) || isEntry(p.getType()))) {
message.append(NULLFLAVOR_SECTION_MESSAGE);
}
}
String keyword = getValidationKeyword(association);
if (keyword != null) {
message.append(markup
? "<b>"
: "");
message.append(keyword);
message.append(markup
? "</b>"
: "");
message.append(" contain ");
} else {
if (property.getUpper() < 0 || property.getUpper() > 1) {
message.append("contains ");
} else {
message.append("contain ");
}
}
message.append(multiplicityElementToggle(property, markup, elementName));
appendConformanceRuleIds(association, message, markup);
if (appendNestedConformanceRules && property.getType() instanceof Class) {
Class inlinedClass = (Class) property.getType();
if (markup && isInlineClass(inlinedClass)) {
StringBuilder sb = new StringBuilder();
appendPropertyComments(sb, property, markup);
appendConformanceRules(sb, inlinedClass, (property.getUpper() == 1
? "This "
: "Such ") +
(property.getUpper() == 1
? elementName
: NameUtilities.pluralize(elementName)) +
" ",
markup);
message.append(" " + sb);
}
}
if (!markup) {
String assocConstraints = computeAssociationConstraints(property, markup);
if (assocConstraints.length() > 0) {
message.append(assocConstraints);
}
}
return message.toString();
}
public static String computeAssociationConstraints(Property property, boolean markup) {
StringBuffer message = new StringBuffer();
Association association = property.getAssociation();
Package xrefSource = UMLUtil.getTopPackage(property);
EntryRelationship entryRelationship = CDAProfileUtil.getEntryRelationship(association);
EntryRelationshipKind typeCode = entryRelationship != null
? entryRelationship.getTypeCode()
: null;
Class endType = (property.getType() instanceof Class)
? (Class) property.getType()
: null;
if (typeCode != null) {
message.append(markup
? "\n<li>"
: " ");
message.append("Contains ");
message.append(markup
? "<tt><b>"
: "").append("@typeCode=\"").append(
markup
? "</b>"
: "");
message.append(typeCode).append("\" ");
message.append(markup
? "</tt>"
: "");
message.append(markup
? "<i>"
: "");
message.append(typeCode.getLiteral());
message.append(markup
? "</i>"
: "");
message.append(markup
? "</li>"
: ", and");
}
// TODO: what I should really do is test for an *implied* ActRelationship or Participation association
if (endType != null && getCDAClass(endType) != null && !(isInlineClass(endType)) &&
!isInlineClass(property.getClass_())) {
message.append(markup
? "\n<li>"
: " ");
message.append("Contains exactly one [1..1] ");
String prefix = !UMLUtil.isSameModel(xrefSource, endType)
? getModelPrefix(endType) + " "
: "";
String xref = computeXref(xrefSource, endType);
boolean showXref = markup && (xref != null);
String format = showXref && xref.endsWith(".html")
? "format=\"html\" "
: "";
message.append(showXref
? "<xref " + format + "href=\"" + xref + "\">"
: "");
message.append(prefix).append(UMLUtil.splitName(endType));
message.append(showXref
? "</xref>"
: "");
String templateId = getTemplateId(endType);
String templateVersion = getTemplateVersion(endType);
if (templateId != null) {
message.append(" (templateId: ");
message.append(markup
? "<tt>"
: "");
message.append(templateId);
// if there is an extension, add a colon followed by its value
if (!StringUtils.isEmpty(templateVersion)) {
message.append(":" + templateVersion);
}
message.append(markup
? "</tt>"
: "");
message.append(")");
}
message.append(markup
? "</li>"
: "");
}
return message.toString();
}
public static String computeConformanceMessage(Property property, boolean markup) {
return computeConformanceMessage(property, markup, UMLUtil.getTopPackage(property));
}
private static String getNameSpacePrefix(Property property) {
Property cdaBaseProperty = CDAModelUtil.getCDAProperty(property);
String nameSpacePrefix = null;
if (cdaBaseProperty != null) {
Stereotype eReferenceStereoetype = cdaBaseProperty.getAppliedStereotype(CDAModelUtil.EREFERENCE);
if (eReferenceStereoetype != null) {
String nameSpace = (String) cdaBaseProperty.getValue(eReferenceStereoetype, CDAModelUtil.XMLNAMESPACE);
if (!StringUtils.isEmpty(nameSpace)) {
Package topPackage = org.openhealthtools.mdht.uml.common.util.UMLUtil.getTopPackage(
cdaBaseProperty.getNearestPackage());
Stereotype ePackageStereoetype = topPackage.getApplicableStereotype(CDAModelUtil.EPACKAGE);
if (ePackageStereoetype != null) {
if (nameSpace.equals(topPackage.getValue(ePackageStereoetype, CDAModelUtil.NSURI))) {
nameSpacePrefix = (String) topPackage.getValue(ePackageStereoetype, CDAModelUtil.NSPREFIX);
} else {
for (Package nestedPackage : topPackage.getNestedPackages()) {
if (nameSpace.equals(nestedPackage.getValue(ePackageStereoetype, CDAModelUtil.NSURI))) {
nameSpacePrefix = (String) nestedPackage.getValue(
ePackageStereoetype, CDAModelUtil.NSPREFIX);
}
}
}
}
}
}
}
return nameSpacePrefix;
}
public static String computeConformanceMessage(Property property, boolean markup, Package xrefSource) {
return computeConformanceMessage(property, markup, xrefSource, true);
}
public static String computeConformanceMessage(Property property, boolean markup, Package xrefSource,
boolean appendNestedConformanceRules) {
if (property.getType() == null) {
System.out.println("Property has null type: " + property.getQualifiedName());
}
if (property.getAssociation() != null && property.isNavigable()) {
return computeAssociationConformanceMessage(property, markup, xrefSource, appendNestedConformanceRules);
}
StringBuffer message = new StringBuffer();
if (!markup) {
message.append(getPrefixedSplitName(property.getClass_())).append(" ");
}
String keyword = getValidationKeywordWithPropertyRange(property);
if (keyword != null) {
message.append(markup
? "<b>"
: "");
message.append(keyword);
message.append(markup
? "</b>"
: "");
message.append(" contain ");
} else {
if (property.getUpper() < 0 || property.getUpper() > 1) {
message.append("contains ");
} else {
message.append("contain ");
}
}
message.append(getMultiplicityText(property));
if (!cardinalityAfterElement) {
message.append(getMultiplicityRange(property));
}
message.append(" ");
message.append(markup
? "<tt><b>"
: "");
// classCode/moodCode
if (isXMLAttribute(property)) {
message.append("@");
}
String propertyPrefix = getNameSpacePrefix(property);
// Try to get CDA Name
IExtensionRegistry reg = Platform.getExtensionRegistry();
IExtensionPoint ep = reg.getExtensionPoint("org.openhealthtools.mdht.uml.cda.core.TransformProvider");
IExtension[] extensions = ep.getExtensions();
TransformProvider newContributor = null;
Property cdaProperty = null;
try {
newContributor = (TransformProvider) extensions[0].getConfigurationElements()[0].createExecutableExtension(
"transform-class");
cdaProperty = newContributor.GetTransform(property);
} catch (Exception e) {
e.printStackTrace();
}
String propertyCdaName = null;
if (cdaProperty != null) {
propertyCdaName = getCDAName(cdaProperty);
} else {
propertyCdaName = getCDAElementName(property);
}
message.append(propertyPrefix != null
? propertyPrefix + ":" + propertyCdaName
: propertyCdaName);
message.append(markup
? "</b>"
: "");
message.append(getBusinessName(property));
if (property.getDefault() != null) {
message.append("=\"").append(property.getDefault()).append("\" ");
}
message.append(markup
? "</tt>"
: "");
if (cardinalityAfterElement) {
message.append(getMultiplicityRange(property));
}
Stereotype nullFlavorSpecification = CDAProfileUtil.getAppliedCDAStereotype(
property, ICDAProfileConstants.NULL_FLAVOR);
Stereotype textValue = CDAProfileUtil.getAppliedCDAStereotype(property, ICDAProfileConstants.TEXT_VALUE);
if (nullFlavorSpecification != null) {
String nullFlavor = getLiteralValue(
property, nullFlavorSpecification, ICDAProfileConstants.NULL_FLAVOR_NULL_FLAVOR);
Enumeration profileEnum = (Enumeration) nullFlavorSpecification.getProfile().getOwnedType(
ICDAProfileConstants.NULL_FLAVOR_KIND);
String nullFlavorLabel = getLiteralValueLabel(
property, nullFlavorSpecification, ICDAProfileConstants.NULL_FLAVOR_NULL_FLAVOR, profileEnum);
if (nullFlavor != null) {
message.append(markup
? "<tt>"
: "");
message.append("/@nullFlavor");
message.append(markup
? "</tt>"
: "");
message.append(" = \"").append(nullFlavor).append("\" ");
message.append(markup
? "<i>"
: "");
message.append(nullFlavorLabel);
message.append(markup
? "</i>"
: "");
}
}
if (textValue != null) {
String value = (String) property.getValue(textValue, ICDAProfileConstants.TEXT_VALUE_VALUE);
if (value != null && value.length() > 0) {
SeverityKind level = (SeverityKind) property.getValue(
textValue, ICDAProfileConstants.VALIDATION_SEVERITY);
message.append(" and ").append(markup
? "<b>"
: "").append(
level != null
? getValidationKeyword(level.getLiteral())
: keyword).append(
markup
? "</b>"
: "").append(" equal \"").append(value).append("\"");
}
}
/*
* Append datatype restriction, if redefined to a specialized type
*/
List<Property> redefinedProperties = UMLUtil.getRedefinedProperties(property);
Property redefinedProperty = redefinedProperties.isEmpty()
? null
: redefinedProperties.get(0);
if (property.getType() != null && ((redefinedProperty == null ||
(!isXMLAttribute(property) && (property.getType() != redefinedProperty.getType()))))) {
message.append(" with " + "@xsi:type=\"");
if (redefinedProperty != null && redefinedProperty.getType() != null &&
redefinedProperty.getType().getName() != null && !redefinedProperty.getType().getName().isEmpty()) {
message.append(redefinedProperty.getType().getName());
} else {
message.append(property.getType().getName());
}
message.append("\"");
}
// for vocab properties, put rule ID at end, use terminology constraint if specified
if (isHL7VocabAttribute(property)) {
String ruleIds = getTerminologyConformanceRuleIds(property);
// if there are terminology rule IDs, then include property rule IDs here
if (ruleIds.length() > 0) {
appendConformanceRuleIds(property, message, markup);
}
} else {
// PropertyConstraint stereotype ruleIds, if specified
appendConformanceRuleIds(property, message, markup);
}
Stereotype codeSystemConstraint = TermProfileUtil.getAppliedStereotype(
property, ITermProfileConstants.CODE_SYSTEM_CONSTRAINT);
Stereotype valueSetConstraint = TermProfileUtil.getAppliedStereotype(
property, ITermProfileConstants.VALUE_SET_CONSTRAINT);
if (codeSystemConstraint != null) {
String vocab = computeCodeSystemMessage(property, markup);
message.append(vocab);
} else if (valueSetConstraint != null) {
String vocab = computeValueSetMessage(property, markup, xrefSource);
message.append(vocab);
} else if (isHL7VocabAttribute(property) && property.getDefault() != null) {
String vocab = computeHL7VocabAttributeMessage(property, markup);
message.append(vocab);
}
// for vocab properties, put rule ID at end, use terminology constraint if specified
if (isHL7VocabAttribute(property)) {
String ruleIds = getTerminologyConformanceRuleIds(property);
if (ruleIds.length() > 0) {
appendTerminologyConformanceRuleIds(property, message, markup);
} else {
appendConformanceRuleIds(property, message, markup);
}
} else {
// rule IDs for the terminology constraint
appendTerminologyConformanceRuleIds(property, message, markup);
}
if (property.getType() != null && appendNestedConformanceRules && property.getType() instanceof Class) {
if (isInlineClass((Class) property.getType())) {
if (isPublishSeperately((Class) property.getType())) {
String xref = (property.getType() instanceof Classifier &&
UMLUtil.isSameProject(property, property.getType()))
? computeXref(xrefSource, (Classifier) property.getType())
: null;
boolean showXref = markup && (xref != null);
if (showXref) {
String format = showXref && xref.endsWith(".html")
? "format=\"html\" "
: "";
message.append(showXref
? "<xref " + format + "href=\"" + xref + "\">"
: "");
message.append(UMLUtil.splitName(property.getType()));
message.append(showXref
? "</xref>"
: "");
}
} else {
StringBuilder sb = new StringBuilder();
boolean hadSideEffect = appendPropertyComments(sb, property, markup);
if (isAppendConformanceRules) {
int len = sb.length();
appendConformanceRules(sb, (Class) property.getType(), "", markup);
hadSideEffect |= sb.length() > len;
}
if (hadSideEffect) {
message.append(" " + sb);
}
}
}
}
return message.toString();
}
/**
* getCDAName
*
* recursively, depth first, check the object graph for a CDA Name using the root of the "redefined"
* property if it exists.
*
* Also handle special cases like sectionId which has a cdaName of ID
*
* @param cdaProperty
* an MDHT property
* @return string
* the calculated CDA name
*/
private static String getCDAName(Property cdaProperty) {
EList<Property> redefines = cdaProperty.getRedefinedProperties();
// if there is a stereotype name, use it
String name = getStereotypeName(cdaProperty);
if (name != null) {
return name;
}
// if there are redefines, check for more but only along the first branch (0)
if (redefines != null && redefines.size() > 0) {
return getCDAName(redefines.get(0));
}
// eventually return the property Name of the root redefined element;
return cdaProperty.getName();
}
/**
* Get the CDA name from a stereotype if it exists
*
* @param cdaProperty
* a Property
* @return the xmlName or null if no stereotype exists
*/
private static String getStereotypeName(Property cdaProperty) {
Stereotype eAttribute = cdaProperty.getAppliedStereotype("Ecore::EAttribute");
String name = null;
if (eAttribute != null) {
name = (String) cdaProperty.getValue(eAttribute, "xmlName");
}
return name;
}
private static void appendSubsetsNotation(Property property, StringBuffer message, boolean markup,
Package xrefSource) {
StringBuffer notation = new StringBuffer();
for (Property subsets : property.getSubsettedProperties()) {
if (subsets.getClass_() == null) {
// eliminate NPE when publishing stereotype references to UML metamodel
continue;
}
if (notation.length() == 0) {
notation.append(" {subsets ");
} else {
notation.append(", ");
}
String xref = computeXref(xrefSource, subsets.getClass_());
boolean showXref = markup && (xref != null);
String format = showXref && xref.endsWith(".html")
? "format=\"html\" "
: "";
notation.append(showXref
? " <xref " + format + "href=\"" + xref + "\">"
: " ");
notation.append(UMLUtil.splitName(subsets.getClass_()));
notation.append(showXref
? "</xref>"
: "");
notation.append("::" + subsets.getName());
}
if (notation.length() > 0) {
notation.append("}");
}
message.append(notation);
}
private static final String[] OL = { "<ol>", "</ol>" };
private static final String[] LI = { "<li>", "</li>" };
private static final String[] NOOL = { "", " " };
private static final String[] NOLI = { "", " " };
static private void appendConformanceRules(StringBuilder appendB, Class umlClass, String prefix, boolean markup) {
String[] ol = markup
? OL
: NOOL;
String[] li = markup
? LI
: NOLI;
StringBuilder sb = new StringBuilder();
boolean hasRules = false;
if (!CDAModelUtil.isInlineClass(umlClass)) {
for (Generalization generalization : umlClass.getGeneralizations()) {
Classifier general = generalization.getGeneral();
if (!RIMModelUtil.isRIMModel(general) && !CDAModelUtil.isCDAModel(general)) {
String message = CDAModelUtil.computeConformanceMessage(generalization, markup);
if (message.length() > 0) {
hasRules = true;
sb.append(li[0] + prefix + message + li[1]);
}
}
}
}
// categorize constraints by constrainedElement name
List<Constraint> unprocessedConstraints = new ArrayList<Constraint>();
// propertyName -> constraints
Map<String, List<Constraint>> constraintMap = new HashMap<String, List<Constraint>>();
// constraint -> sub-constraints
Map<Constraint, List<Constraint>> subConstraintMap = new HashMap<Constraint, List<Constraint>>();
for (Constraint constraint : umlClass.getOwnedRules()) {
unprocessedConstraints.add(constraint);
// Do not associate logical constraints with a property because they are a class and not a property constraint
if (CDAProfileUtil.getLogicalConstraint(constraint) == null) {
for (Element element : constraint.getConstrainedElements()) {
if (element instanceof Property) {
String name = ((Property) element).getName();
List<Constraint> rules = constraintMap.get(name);
if (rules == null) {
rules = new ArrayList<Constraint>();
constraintMap.put(name, rules);
}
rules.add(constraint);
} else if (element instanceof Constraint) {
Constraint subConstraint = (Constraint) element;
List<Constraint> rules = subConstraintMap.get(subConstraint);
if (rules == null) {
rules = new ArrayList<Constraint>();
subConstraintMap.put(subConstraint, rules);
}
rules.add(constraint);
}
}
}
}
PropertyList propertyList = new PropertyList(umlClass, CDAModelUtil.isInlineClass(umlClass));
// XML attributes
for (Property property : propertyList.getAttributes()) {
hasRules = hasRules | appendPropertyList(
umlClass, property, markup, ol, sb, prefix, li, constraintMap, unprocessedConstraints,
subConstraintMap);
}
// XML elements
for (Property property : propertyList.getAssociationEnds()) {
hasRules = hasRules | appendPropertyList(
umlClass, property, markup, ol, sb, prefix, li, constraintMap, unprocessedConstraints,
subConstraintMap);
}
for (Constraint constraint : unprocessedConstraints) {
hasRules = true;
sb.append(li[0] + prefix + CDAModelUtil.computeConformanceMessage(constraint, markup) + li[1]);
}
if (hasRules) {
appendB.append(ol[0]);
appendB.append(sb);
appendB.append(ol[1]);
}
}
private static boolean appendPropertyList(Element umlClass, Property property, boolean markup, String[] ol,
StringBuilder sb, String prefix, String[] li, Map<String, List<Constraint>> constraintMap,
List<Constraint> unprocessedConstraints, Map<Constraint, List<Constraint>> subConstraintMap) {
boolean result = false;
if (!CDAModelUtil.isCDAModel(umlClass) && !CDAModelUtil.isCDAModel(property) &&
!CDAModelUtil.isDatatypeModel(property)) {
result = true;
String ccm = CDAModelUtil.computeConformanceMessage(property, markup);
boolean order = ccm.trim().endsWith(ol[1]);
boolean currentlyItem = false;
if (order) {
int olIndex = ccm.lastIndexOf(ol[1]);
ccm = ccm.substring(0, olIndex);
currentlyItem = ccm.trim().endsWith(li[1]);
}
sb.append(li[0] + prefix + ccm);
StringBuilder propertyComments = new StringBuilder();
currentlyItem &= appendPropertyComments(propertyComments, property, markup);
if (currentlyItem) {
sb.append(li[0]).append(propertyComments).append(li[1]);
}
appendPropertyRules(sb, property, constraintMap, subConstraintMap, unprocessedConstraints, markup, !order);
if (order) {
sb.append(ol[1]);
}
sb.append(li[1]);
}
return result;
}
private static boolean appendPropertyComments(StringBuilder sb, Property property, boolean markup) {
// INLINE
Association association = property.getAssociation();
int startingStrLength = sb.length();
if (association != null && association.getOwnedComments().size() > 0) {
if (markup) {
sb.append("<p><lines><i>");
}
for (Comment comment : association.getOwnedComments()) {
sb.append(CDAModelUtil.fixNonXMLCharacters(comment.getBody()));
}
if (markup) {
sb.append("</i></lines></p>");
}
}
if (property.getOwnedComments().size() > 0) {
if (markup) {
sb.append("<p><lines><i>");
}
for (Comment comment : property.getOwnedComments()) {
sb.append(CDAModelUtil.fixNonXMLCharacters(comment.getBody()));
}
if (markup) {
sb.append("</i></lines></p>");
}
}
return sb.length() > startingStrLength;
}
private static void appendPropertyRules(StringBuilder sb, Property property,
Map<String, List<Constraint>> constraintMap, Map<Constraint, List<Constraint>> subConstraintMap,
List<Constraint> unprocessedConstraints, boolean markup, boolean newOrder) {
String[] ol = markup && newOrder
? OL
: NOOL;
String[] li = markup
? LI
: NOLI;
// association typeCode and property type
String assocConstraints = "";
if (property.getAssociation() != null) {
assocConstraints = CDAModelUtil.computeAssociationConstraints(property, markup);
}
StringBuffer ruleConstraints = new StringBuffer();
List<Constraint> rules = constraintMap.get(property.getName());
if (rules != null && !rules.isEmpty()) {
for (Constraint constraint : rules) {
unprocessedConstraints.remove(constraint);
ruleConstraints.append(li[0] + CDAModelUtil.computeConformanceMessage(constraint, markup));
appendSubConstraintRules(ruleConstraints, constraint, subConstraintMap, unprocessedConstraints, markup);
ruleConstraints.append(li[1]);
}
}
if (assocConstraints.length() > 0 || ruleConstraints.length() > 0) {
sb.append(ol[0]);
sb.append(assocConstraints);
sb.append(ruleConstraints);
sb.append(ol[1]);
}
}
private static void appendSubConstraintRules(StringBuffer ruleConstraints, Constraint constraint,
Map<Constraint, List<Constraint>> subConstraintMap, List<Constraint> unprocessedConstraints,
boolean markup) {
String[] ol;
String[] li;
if (markup) {
ol = OL;
li = LI;
} else {
ol = NOOL;
li = NOLI;
}
List<Constraint> subConstraints = subConstraintMap.get(constraint);
if (subConstraints != null && subConstraints.size() > 0) {
ruleConstraints.append(ol[0]);
for (Constraint subConstraint : subConstraints) {
unprocessedConstraints.remove(subConstraint);
ruleConstraints.append(li[0] + CDAModelUtil.computeConformanceMessage(subConstraint, markup));
appendSubConstraintRules(
ruleConstraints, subConstraint, subConstraintMap, unprocessedConstraints, markup);
ruleConstraints.append(li[1]);
}
ruleConstraints.append(ol[1]);
}
}
private static boolean isHL7VocabAttribute(Property property) {
String name = property.getName();
return "classCode".equals(name) || "moodCode".equals(name) || "typeCode".equals(name);
}
private static String computeHL7VocabAttributeMessage(Property property, boolean markup) {
StringBuffer message = new StringBuffer();
Class rimClass = RIMModelUtil.getRIMClass(property.getClass_());
String code = property.getDefault();
String displayName = null;
String codeSystemId = null;
String codeSystemName = null;
if (rimClass != null) {
if ("Act".equals(rimClass.getName())) {
if ("classCode".equals(property.getName())) {
codeSystemName = "HL7ActClass";
codeSystemId = "2.16.840.1.113883.5.6";
if ("ACT".equals(code)) {
displayName = "Act";
} else if ("OBS".equals(code)) {
displayName = "Observation";
}
} else if ("moodCode".equals(property.getName())) {
codeSystemName = "HL7ActMood";
codeSystemId = "2.16.840.1.113883.5.1001";
if ("EVN".equals(code)) {
displayName = "Event";
}
}
}
}
if (displayName != null) {
message.append(markup
? "<i>"
: "");
message.append(displayName);
message.append(markup
? "</i>"
: "");
}
if (codeSystemId != null || codeSystemName != null) {
message.append(" (CodeSystem:");
message.append(markup
? "<tt>"
: "");
if (codeSystemId != null) {
message.append(" ").append(codeSystemId);
}
if (codeSystemName != null) {
message.append(" ").append(codeSystemName);
}
message.append(markup
? "</tt>"
: "");
message.append(")");
}
return message.toString();
}
private static String computeCodeSystemMessage(Property property, boolean markup) {
Stereotype codeSystemConstraintStereotype = TermProfileUtil.getAppliedStereotype(
property, ITermProfileConstants.CODE_SYSTEM_CONSTRAINT);
CodeSystemConstraint codeSystemConstraint = TermProfileUtil.getCodeSystemConstraint(property);
String keyword = getValidationKeyword(property, codeSystemConstraintStereotype);
String id = null;
String name = null;
String code = null;
String displayName = null;
if (codeSystemConstraint != null) {
if (codeSystemConstraint.getReference() != null) {
CodeSystemVersion codeSystemVersion = codeSystemConstraint.getReference();
id = codeSystemVersion.getIdentifier();
name = codeSystemVersion.getEnumerationName();
codeSystemVersion.getVersion();
} else {
id = codeSystemConstraint.getIdentifier();
name = codeSystemConstraint.getName();
codeSystemConstraint.getVersion();
}
codeSystemConstraint.getBinding();
code = codeSystemConstraint.getCode();
displayName = codeSystemConstraint.getDisplayName();
}
StringBuffer message = new StringBuffer();
if (code != null) {
message.append(markup
? "<tt><b>"
: "");
// single value binding
message.append("/@code");
message.append(markup
? "</b>"
: "");
message.append("=\"").append(code).append("\" ");
message.append(markup
? "</tt>"
: "");
if (displayName != null) {
message.append(markup
? "<i>"
: "");
message.append(displayName);
message.append(markup
? "</i>"
: "");
}
} else {
// capture and return proper xml binding message based on mandatory or not
message.append(mandatoryOrNotMessage(property));
if (keyword != null) {
message.append(markup
? "<b>"
: "");
message.append(keyword);
message.append(markup
? "</b>"
: "");
message.append(" be");
} else {
message.append("is");
}
message.append(" selected from");
}
if (id != null || name != null) {
message.append(" (CodeSystem:");
message.append(markup
? "<tt>"
: "");
if (id != null) {
message.append(" ").append(id);
}
if (name != null) {
message.append(" ").append(name);
}
message.append(markup
? "</tt>"
: "");
message.append(")");
}
return message.toString();
}
private static String computeValueSetMessage(Property property, boolean markup, Package xrefSource) {
Stereotype valueSetConstraintStereotype = TermProfileUtil.getAppliedStereotype(
property, ITermProfileConstants.VALUE_SET_CONSTRAINT);
ValueSetConstraint valueSetConstraint = TermProfileUtil.getValueSetConstraint(property);
String keyword = getValidationKeyword(property, valueSetConstraintStereotype);
String id = null;
String name = null;
String version = null;
BindingKind binding = null;
String xref = null;
String xrefFormat = "";
boolean showXref = false;
if (valueSetConstraint != null) {
if (valueSetConstraint.getReference() != null) {
ValueSetVersion valueSetVersion = valueSetConstraint.getReference();
id = valueSetVersion.getIdentifier();
name = valueSetVersion.getEnumerationName();
version = valueSetVersion.getVersion();
binding = valueSetVersion.getBinding();
if (valueSetVersion.getBase_Enumeration() != null) {
xref = computeTerminologyXref(property.getClass_(), valueSetVersion.getBase_Enumeration());
}
showXref = markup && (xref != null);
xrefFormat = showXref && xref.endsWith(".html")
? "format=\"html\" "
: "";
} else {
id = valueSetConstraint.getIdentifier();
name = valueSetConstraint.getName();
version = valueSetConstraint.getVersion();
binding = valueSetConstraint.getBinding();
}
}
StringBuffer message = new StringBuffer();
// capture and return proper xml binding message based on mandatory or not
message.append(mandatoryOrNotMessage(property));
if (keyword != null) {
message.append(markup
? "<b>"
: "");
message.append(keyword);
message.append(markup
? "</b>"
: "");
message.append(" be");
} else {
message.append("is");
}
message.append(" selected from ValueSet");
message.append(markup
? "<tt>"
: "");
if (name != null) {
message.append(" ");
message.append(showXref
? "<xref " + xrefFormat + "href=\"" + xref + "\">"
: "");
message.append(name);
message.append(showXref
? "</xref>"
: "");
}
if (id != null) {
message.append(" ").append(id);
}
message.append(markup
? "</tt>"
: "");
message.append(markup
? "<b>"
: "");
message.append(" ").append(binding.getName().toUpperCase());
message.append(markup
? "</b>"
: "");
if (BindingKind.STATIC == binding && version != null) {
message.append(" ").append(version);
}
return message.toString();
}
public static String computeConformanceMessage(Constraint constraint, boolean markup) {
LogicalConstraint logicConstraint = CDAProfileUtil.getLogicalConstraint(constraint);
if (logicConstraint != null) {
return computeLogicalConformanceMessage(constraint, logicConstraint, markup);
} else {
return computeCustomConformanceMessage(constraint, markup);
}
}
private static String computeCustomConformanceMessage(Constraint constraint, boolean markup) {
StringBuffer message = new StringBuffer();
String strucTextBody = null;
String analysisBody = null;
Map<String, String> langBodyMap = new HashMap<String, String>();
CDAProfileUtil.getLogicalConstraint(constraint);
ValueSpecification spec = constraint.getSpecification();
if (spec instanceof OpaqueExpression) {
for (int i = 0; i < ((OpaqueExpression) spec).getLanguages().size(); i++) {
String lang = ((OpaqueExpression) spec).getLanguages().get(i);
String body = ((OpaqueExpression) spec).getBodies().get(i);
if ("StrucText".equals(lang)) {
strucTextBody = body;
} else if ("Analysis".equals(lang)) {
analysisBody = body;
} else {
langBodyMap.put(lang, body);
}
}
}
String displayBody = null;
if (strucTextBody != null && strucTextBody.trim().length() > 0) {
// TODO if markup, parse strucTextBody and insert DITA markup
displayBody = strucTextBody;
} else if (analysisBody != null && analysisBody.trim().length() > 0) {
Boolean ditaEnabled = false;
try {
Stereotype stereotype = CDAProfileUtil.getAppliedCDAStereotype(
constraint, ICDAProfileConstants.CONSTRAINT_VALIDATION);
ditaEnabled = (Boolean) constraint.getValue(stereotype, ICDAProfileConstants.CONSTRAINT_DITA_ENABLED);
} catch (IllegalArgumentException e) { /* Swallow this */
}
if (markup && !ditaEnabled) {
// escape non-dita markup in analysis text
displayBody = escapeMarkupCharacters(analysisBody);
// change severity words to bold text
displayBody = replaceSeverityWithBold(displayBody);
} else {
displayBody = analysisBody;
}
}
if (displayBody == null) {
List<Stereotype> stereotypes = constraint.getAppliedStereotypes();
if (stereotypes.isEmpty()) {
// This should never happen but in case it does we deal with it appropriately
// by bypassing custom constraint message additions
return "";
}
}
if (!markup) {
message.append(getPrefixedSplitName(constraint.getContext())).append(" ");
}
if (displayBody == null || !containsSeverityWord(displayBody)) {
String keyword = getValidationKeyword(constraint);
if (keyword == null) {
keyword = "SHALL";
}
message.append(markup
? "<b>"
: "");
message.append(keyword);
message.append(markup
? "</b>"
: "");
message.append(" satisfy: ");
}
if (displayBody == null) {
message.append(constraint.getName());
} else {
message.append(displayBody);
}
appendConformanceRuleIds(constraint, message, markup);
if (!markup) {
// remove line feeds
int index;
while ((index = message.indexOf("\r")) >= 0) {
message.deleteCharAt(index);
}
while ((index = message.indexOf("\n")) >= 0) {
message.deleteCharAt(index);
if (message.charAt(index) != ' ') {
message.insert(index, " ");
}
}
}
return message.toString();
}
private static String computeLogicalConformanceMessage(Constraint constraint, LogicalConstraint logicConstraint,
boolean markup) {
StringBuffer message = new StringBuffer();
logicConstraint.getMessage();
String keyword = getValidationKeyword(constraint);
if (keyword == null) {
keyword = "SHALL";
}
// Wording for IFTHEN - IF xxx then SHALL yyy
if (!logicConstraint.getOperation().equals(LogicalOperator.IFTHEN)) {
message.append(markup
? "<b>"
: "");
message.append(keyword);
message.append(markup
? "</b>"
: "");
}
switch (logicConstraint.getOperation()) {
case XOR:
message.append(" contain one and only one of the following ");
break;
case AND:
message.append(" contain all of the following ");
break;
case OR:
message.append(" contain one or more of the following ");
case IFTHEN:
message.append("if ");
break;
case NOTBOTH:
message.append(" contain zero or one of the following but not both ");
break;
default:
message.append(" satisfy the following ");
break;
}
if (logicConstraint.getOperation().equals(LogicalOperator.IFTHEN) &&
constraint.getConstrainedElements().size() == 2) {
String propertyKeyword = getValidationKeyword(constraint.getConstrainedElements().get(0));
if (propertyKeyword != null) {
message.append(
computeConformanceMessage(constraint.getConstrainedElements().get(0), markup).replace(
propertyKeyword, ""));
} else {
message.append(computeConformanceMessage(constraint.getConstrainedElements().get(0), markup));
}
message.append(" then it ").append(markup
? "<lines>"
: "").append(
markup
? "<b>"
: "").append(keyword).append(
markup
? "</b> "
: " ");
message.append(computeConformanceMessage(constraint.getConstrainedElements().get(1), markup));
message.append(markup
? "</lines>"
: "");
} else {
if (markup) {
message.append("<ul>");
}
for (Element element : constraint.getConstrainedElements()) {
message.append(LI[0]);
message.append(computeConformanceMessage(element, markup));
message.append(LI[1]);
}
if (markup) {
message.append("</ul>");
}
}
appendConformanceRuleIds(constraint, message, markup);
return message.toString();
}
private static boolean containsSeverityWord(String text) {
return text.indexOf("SHALL") >= 0 || text.indexOf("SHOULD") >= 0 || text.indexOf("MAY") >= 0;
}
private static String replaceSeverityWithBold(String input) {
String output;
output = input.replaceAll("SHALL", "<b>SHALL</b>");
output = output.replaceAll("SHOULD", "<b>SHOULD</b>");
output = output.replaceAll("MAY", "<b>MAY</b>");
output = output.replaceAll("\\<b>SHALL\\</b> NOT", "<b>SHALL NOT</b>");
output = output.replaceAll("\\<b>SHOULD\\</b> NOT", "<b>SHOULD NOT</b>");
return output;
}
/**
* FindResourcesByNameVisitor searches the resource for resources of a particular name
* You would think there was a method for this already but i could not find it
*
* @author seanmuir
*
*/
public static class FindResourcesByNameVisitor implements IResourceVisitor {
private String resourceName;
private ArrayList<IResource> resources = new ArrayList<IResource>();
/**
* @return the resources
*/
public ArrayList<IResource> getResources() {
return resources;
}
/**
* @param resourceName
*/
public FindResourcesByNameVisitor(String resourceName) {
super();
this.resourceName = resourceName;
}
/*
* (non-Javadoc)
*
* @see org.eclipse.core.resources.IResourceVisitor#visit(org.eclipse.core.resources.IResource)
*/
public boolean visit(IResource arg0) throws CoreException {
if (resourceName != null && resourceName.equals(arg0.getName())) {
resources.add(arg0);
}
return true;
}
}
public static IProject getElementModelProject(Element element) {
try {
Package elementPackage = UMLUtil.getTopPackage(element);
if (elementPackage != null && elementPackage.eResource() != null) {
FindResourcesByNameVisitor visitor = new FindResourcesByNameVisitor(
elementPackage.eResource().getURI().lastSegment());
IWorkspace iw = org.eclipse.core.resources.ResourcesPlugin.getWorkspace();
iw.getRoot().accept(visitor);
if (!visitor.getResources().isEmpty()) {
return visitor.getResources().get(0).getProject();
}
}
} catch (CoreException e) {
// If there is an issue with the workspace - return null
}
return null;
}
public static IProject getModelDocProject(IProject modelProject) {
if (modelProject != null && modelProject.exists()) {
return org.eclipse.core.resources.ResourcesPlugin.getWorkspace().getRoot().getProject(
modelProject.getName().replace(".model", ".doc"));
}
return null;
}
/**
* computeXref returns the XREF for DITA publication
*
* TODO Refactor and move out of model util
*
* @param source
* @param target
* @return
*/
public static String computeXref(Element source, Classifier target) {
if (target == null) {
return null;
}
if (target instanceof Enumeration) {
return computeTerminologyXref(source, (Enumeration) target);
}
if (UMLUtil.isSameProject(source, target)) {
return "../" + normalizeCodeName(target.getName()) + ".dita";
}
// If the model project is available (should be) and the dita content is part of the doc project
if (!isCDAModel(target)) {
IProject sourceProject = getElementModelProject(source);
sourceProject = getModelDocProject(sourceProject);
IProject targetProject = getElementModelProject(target);
targetProject = getModelDocProject(targetProject);
if (targetProject != null && sourceProject != null) {
IPath projectPath = new Path("/dita/classes/" + targetProject.getName());
IFolder referenceDitaFolder = sourceProject.getFolder(projectPath);
if (referenceDitaFolder.exists()) {
return "../" + targetProject.getName() + "/classes/" + normalizeCodeName(target.getName()) +
".dita";
}
}
String pathFolder = "classes";
String basePackage = "";
String prefix = "";
String packageName = target.getNearestPackage().getName();
if (RIMModelUtil.RIM_PACKAGE_NAME.equals(packageName)) {
basePackage = "org.openhealthtools.mdht.uml.hl7.rim";
} else if (CDA_PACKAGE_NAME.equals(packageName)) {
basePackage = "org.openhealthtools.mdht.uml.cda";
} else {
basePackage = getModelBasePackage(target);
prefix = getModelNamespacePrefix(target);
}
if (basePackage == null || basePackage.trim().length() == 0) {
basePackage = "org.openhealthtools.mdht.uml.cda";
}
if (prefix != null && prefix.trim().length() > 0) {
prefix += ".";
}
return INFOCENTER_URL + "/topic/" + basePackage + "." + prefix + "doc/" + pathFolder + "/" +
normalizeCodeName(target.getName()) + ".html";
}
return null;
}
protected static String computeTerminologyXref(Element source, Enumeration target) {
String href = null;
if (UMLUtil.isSameProject(source, target)) {
href = "../../terminology/" + normalizeCodeName(target.getName()) + ".dita";
}
return href;
}
public static Property getNavigableEnd(Association association) {
Property navigableEnd = null;
for (Property end : association.getMemberEnds()) {
if (end.isNavigable()) {
if (navigableEnd != null) {
return null; // multiple navigable ends
}
navigableEnd = end;
}
}
return navigableEnd;
}
/**
* getExtensionNamespace returns the name space from a extension package in the CDA model
*
* @param type
* @return
*/
private static String getExtensionNamespace(Type type) {
String nameSpace = null;
if (type != null && type.getNearestPackage() != null &&
!CDA_PACKAGE_NAME.equals(type.getNearestPackage().getName())) {
Stereotype ecoreStereotype = type.getNearestPackage().getAppliedStereotype(EPACKAGE);
if (ecoreStereotype != null) {
Object object = type.getNearestPackage().getValue(ecoreStereotype, NSPREFIX);
if (object instanceof String) {
nameSpace = (String) object;
}
}
}
return nameSpace;
}
public static String getNameSpacePrefix(Class cdaSourceClass) {
if (cdaSourceClass != null && cdaSourceClass.getPackage() != null &&
!CDA_PACKAGE_NAME.equals(cdaSourceClass.getPackage().getName())) {
Stereotype ecoreStereotype = cdaSourceClass.getPackage().getAppliedStereotype(EPACKAGE);
if (ecoreStereotype != null) {
Object object = cdaSourceClass.getPackage().getValue(ecoreStereotype, NSPREFIX);
if (object instanceof String) {
return (String) object;
}
}
}
return null;
}
/**
* getCDAElementName - Returns the CDA Element name as a string
*
* @TODO Refactor to use org.openhealthtools.mdht.uml.transform.ecore.TransformAbstract.getInitialProperty(Property)
*
* Currently walk the redefines to see if we can match the CDA property using the name and type
* If none found - for backwards compatibility we look for a property in the base class with a matching type which is potential error prone
* If none still - leverage the getassociation
*
* @param property
* @return
*/
public static String getCDAElementName(Property property) {
String elementName = null;
if (property.getType() instanceof Class) {
Class cdaSourceClass = getCDAClass(property.getClass_());
if (cdaSourceClass != null) {
// First check for definitions
for (Property redefinedProperty : property.getRedefinedProperties()) {
// This will never succeed for associations, does not include ActRelationship
if (redefinedProperty.getType() != null) {
Property cdaProperty = cdaSourceClass.getOwnedAttribute(
redefinedProperty.getName(), getCDAClass((Classifier) redefinedProperty.getType()));
if (cdaProperty != null && cdaProperty.getName() != null) {
String modelPrefix = getExtensionNamespace(cdaProperty.getType());
elementName = !StringUtils.isEmpty(modelPrefix)
? modelPrefix + ":" + cdaProperty.getName()
: cdaProperty.getName();
break;
}
}
}
// Next check using property type and name
if (elementName == null) {
Property cdaProperty = cdaSourceClass.getOwnedAttribute(
property.getName(), getCDAClass((Classifier) property.getType()));
if (cdaProperty != null && cdaProperty.getName() != null) {
String modelPrefix = getExtensionNamespace(cdaProperty.getType());
elementName = !StringUtils.isEmpty(modelPrefix)
? modelPrefix + ":" + cdaProperty.getName()
: cdaProperty.getName();
}
}
// Ultimately use original logic for backwards compatibility
if (elementName == null) {
Property cdaProperty = cdaSourceClass.getOwnedAttribute(
null, getCDAClass((Classifier) property.getType()));
if (cdaProperty != null && cdaProperty.getName() != null) {
String modelPrefix = getExtensionNamespace(cdaProperty.getType());
elementName = !StringUtils.isEmpty(modelPrefix)
? modelPrefix + ":" + cdaProperty.getName()
: cdaProperty.getName();
}
}
}
}
// look for CDA association class element name, e.g. "component"
if (elementName == null) {
elementName = getCDAAssociationElementName(property);
}
if (elementName == null) {
elementName = property.getName();
}
return elementName;
}
public static String getCDAAssociationElementName(Property property) {
Class cdaSourceClass = getCDAClass(property.getClass_());
Class endType = (property.getType() instanceof Class)
? (Class) property.getType()
: null;
Class cdaTargetClass = endType != null
? getCDAClass(endType)
: null;
// This is incomplete determination of XML element name, but same logic as used in model transform
String elementName = null;
if (cdaSourceClass == null) {
elementName = property.getName();
} else if ("ClinicalDocument".equals(cdaSourceClass.getName()) &&
(CDAModelUtil.isSection(cdaTargetClass) || CDAModelUtil.isClinicalStatement(cdaTargetClass))) {
elementName = "component";
} else if (CDAModelUtil.isSection(cdaSourceClass) && (CDAModelUtil.isSection(cdaTargetClass))) {
elementName = "component";
} else if (CDAModelUtil.isSection(cdaSourceClass) &&
(CDAModelUtil.isClinicalStatement(cdaTargetClass) || CDAModelUtil.isEntry(cdaTargetClass))) {
elementName = "entry";
} else if (CDAModelUtil.isOrganizer(cdaSourceClass) && CDAModelUtil.isClinicalStatement(cdaTargetClass)) {
elementName = "component";
} else if (CDAModelUtil.isClinicalStatement(cdaSourceClass) &&
CDAModelUtil.isClinicalStatement(cdaTargetClass)) {
elementName = "entryRelationship";
} else if (CDAModelUtil.isClinicalStatement(cdaSourceClass) && cdaTargetClass != null &&
"ParticipantRole".equals(cdaTargetClass.getName())) {
elementName = "participant";
} else if (CDAModelUtil.isClinicalStatement(cdaSourceClass) && cdaTargetClass != null &&
"AssignedEntity".equals(cdaTargetClass.getName())) {
elementName = "performer";
}
return elementName;
}
private static String getMultiplicityRange(Property property) {
StringBuffer message = new StringBuffer();
String lower = Integer.toString(property.getLower());
String upper = property.getUpper() == -1
? "*"
: Integer.toString(property.getUpper());
message.append(" [").append(lower).append("..").append(upper).append("]");
return message.toString();
}
private static String getMultiplicityText(Property property) {
StringBuffer message = new StringBuffer();
if (property.getLower() == property.getUpper()) {
// Upper and lower equal and not zero
if (property.getLower() != 0) {
message.append("exactly ").append(convertNumberToWords(property.getUpper()));
}
} else if (property.getLower() == 0) {
// Lower is zero
if (property.getUpper() == 0) {
} else if (property.getUpper() == 1) {
message.append("zero or one");
} else if (property.getUpper() == -1) {
message.append("zero or more");
} else {
message.append("not more than " + convertNumberToWords(property.getUpper()));
}
} else if (property.getLower() == 1) {
// Lower is one
if (property.getUpper() == -1) {
message.append("at least one");
} else {
message.append(
"at least " + convertNumberToWords(property.getLower()) + " and not more than " +
convertNumberToWords(property.getUpper()));
}
} else {
// Lower is greater then 1
message.append("at least " + convertNumberToWords(property.getLower()));
if (property.getUpper() != -1) {
message.append(" and not more than " + convertNumberToWords(property.getUpper()));
}
}
return message.toString();
}
// This snippet may be used freely, as long as the authorship note remains in the source code.
private static final String[] lowNames = {
"zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "eleven", "twelve",
"thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen" };
private static final String[] tensNames = {
"twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety" };
private static final String[] bigNames = { "thousand", "million", "billion" };
private static String convertNumberToWords(int n) {
if (n < 0) {
return "minus " + convertNumberToWords(-n);
}
if (n <= 999) {
return convert999(n);
}
String s = null;
int t = 0;
while (n > 0) {
if (n % 1000 != 0) {
String s2 = convert999(n % 1000);
if (t > 0) {
s2 = s2 + " " + bigNames[t - 1];
}
if (s == null) {
s = s2;
} else {
s = s2 + ", " + s;
}
}
n /= 1000;
t++;
}
return s;
}
// Range 0 to 999.
private static String convert999(int n) {
String s1 = lowNames[n / 100] + " hundred";
String s2 = convert99(n % 100);
if (n <= 99) {
return s2;
} else if (n % 100 == 0) {
return s1;
} else {
return s1 + " " + s2;
}
}
// Range 0 to 99.
private static String convert99(int n) {
if (n < 20) {
return lowNames[n];
}
String s = tensNames[n / 10 - 2];
if (n % 10 == 0) {
return s;
}
return s + "-" + lowNames[n % 10];
}
public static boolean isXMLAttribute(Property property) {
Property cdaProperty = getCDAProperty(property);
if (cdaProperty != null) {
Stereotype eAttribute = cdaProperty.getAppliedStereotype("Ecore::EAttribute");
if (eAttribute != null) {
return true;
}
}
return false;
}
private static String getMultiplicityRange(Class template) {
String templateId = null;
Stereotype hl7Template = CDAProfileUtil.getAppliedCDAStereotype(template, ICDAProfileConstants.CDA_TEMPLATE);
if (hl7Template != null && template.hasValue(hl7Template, ICDAProfileConstants.CDA_TEMPLATE_MULTIPLICITY)) {
templateId = (String) template.getValue(hl7Template, ICDAProfileConstants.CDA_TEMPLATE_MULTIPLICITY);
} else {
for (Classifier parent : template.getGenerals()) {
templateId = getMultiplicityRange((Class) parent);
if (templateId != null) {
break;
}
}
}
return templateId;
}
public static String getTemplateId(Class template) {
String templateId = null;
Stereotype hl7Template = CDAProfileUtil.getAppliedCDAStereotype(template, ICDAProfileConstants.CDA_TEMPLATE);
if (hl7Template != null) {
templateId = (String) template.getValue(hl7Template, ICDAProfileConstants.CDA_TEMPLATE_TEMPLATE_ID);
} else {
for (Classifier parent : template.getGenerals()) {
templateId = getTemplateId((Class) parent);
if (templateId != null) {
break;
}
}
}
return templateId;
}
public static String getTemplateVersion(Class template) {
String templateVersion = null;
Stereotype hl7Template = CDAProfileUtil.getAppliedCDAStereotype(template, ICDAProfileConstants.CDA_TEMPLATE);
if (hl7Template != null) {
templateVersion = (String) template.getValue(hl7Template, ICDAProfileConstants.CDA_TEMPLATE_VERSION);
} else {
for (Classifier parent : template.getGenerals()) {
templateVersion = getTemplateId((Class) parent);
if (templateVersion != null) {
break;
}
}
}
return templateVersion;
}
public static String getModelPrefix(Element element) {
String prefix = null;
Package thePackage = UMLUtil.getTopPackage(element);
if (thePackage != null) {
Stereotype codegenSupport = CDAProfileUtil.getAppliedCDAStereotype(
thePackage, ICDAProfileConstants.CODEGEN_SUPPORT);
if (codegenSupport != null) {
prefix = (String) thePackage.getValue(codegenSupport, ICDAProfileConstants.CODEGEN_SUPPORT_PREFIX);
} else if (CDA_PACKAGE_NAME.equals(thePackage.getName())) {
prefix = "CDA";
} else if (RIMModelUtil.RIM_PACKAGE_NAME.equals(thePackage.getName())) {
prefix = "RIM";
}
}
return prefix != null
? prefix
: "";
}
public static String getModelNamespacePrefix(Element element) {
String prefix = null;
Package model = UMLUtil.getTopPackage(element);
Stereotype codegenSupport = CDAProfileUtil.getAppliedCDAStereotype(model, ICDAProfileConstants.CODEGEN_SUPPORT);
if (codegenSupport != null) {
prefix = (String) model.getValue(codegenSupport, ICDAProfileConstants.CODEGEN_SUPPORT_NS_PREFIX);
}
return prefix;
}
public static String getModelBasePackage(Element element) {
String basePackage = null;
Package model = UMLUtil.getTopPackage(element);
Stereotype codegenSupport = CDAProfileUtil.getAppliedCDAStereotype(model, ICDAProfileConstants.CODEGEN_SUPPORT);
if (codegenSupport != null) {
basePackage = (String) model.getValue(codegenSupport, ICDAProfileConstants.CODEGEN_SUPPORT_BASE_PACKAGE);
}
return basePackage;
}
public static String getEcorePackageURI(Element element) {
String nsURI = null;
Package model = UMLUtil.getTopPackage(element);
Stereotype codegenSupport = CDAProfileUtil.getAppliedCDAStereotype(model, ICDAProfileConstants.CODEGEN_SUPPORT);
if (codegenSupport != null) {
nsURI = (String) model.getValue(codegenSupport, ICDAProfileConstants.CODEGEN_SUPPORT_NS_URI);
}
if (nsURI == null) {
// for base models without codegenSupport
if (model.getName().equals("cda")) {
nsURI = "urn:hl7-org:v3";
} else if (model.getName().equals("datatypes")) {
nsURI = "http:
} else if (model.getName().equals("vocab")) {
nsURI = "http:
}
}
return nsURI;
}
public static String getPrefixedSplitName(NamedElement element) {
StringBuffer buffer = new StringBuffer();
String modelPrefix = getModelPrefix(element);
if (modelPrefix != null && modelPrefix.length() > 0) {
buffer.append(modelPrefix).append(" ");
}
buffer.append(UMLUtil.splitName(element));
return buffer.toString();
}
/**
* Returns a list conformance rule IDs.
*/
public static List<String> getConformanceRuleIdList(Element element) {
List<String> ruleIds = new ArrayList<String>();
Stereotype validationSupport = CDAProfileUtil.getAppliedCDAStereotype(element, ICDAProfileConstants.VALIDATION);
if (validationSupport != null) {
Validation validation = (Validation) element.getStereotypeApplication(validationSupport);
for (String ruleId : validation.getRuleId()) {
ruleIds.add(ruleId);
}
}
return ruleIds;
}
protected static void appendTerminologyConformanceRuleIds(Property property, StringBuffer message, boolean markup) {
String ruleIds = getTerminologyConformanceRuleIds(property);
if (ruleIds.length() > 0) {
message.append(" (");
message.append(ruleIds);
message.append(")");
}
}
protected static void appendConformanceRuleIds(Property property, StringBuffer message, boolean markup) {
String ruleIds = getConformanceRuleIds(property);
if (ruleIds.length() > 0) {
message.append(" (");
message.append(ruleIds);
message.append(")");
}
}
protected static void appendConformanceRuleIds(Association association, StringBuffer message, boolean markup) {
String ruleIds = getConformanceRuleIds(association);
if (ruleIds.length() > 0) {
message.append(" (");
message.append(ruleIds);
message.append(")");
}
}
protected static void appendConformanceRuleIds(Element element, StringBuffer message, boolean markup) {
String ruleIds = getConformanceRuleIds(element);
if (ruleIds.length() > 0) {
message.append(" (");
message.append(ruleIds);
message.append(")");
}
}
protected static void appendConformanceRuleIds(Element element, Stereotype stereotype, StringBuffer message,
boolean markup) {
String ruleIds = getConformanceRuleIds(element, stereotype);
if (ruleIds.length() > 0) {
message.append(" (");
message.append(ruleIds);
message.append(")");
}
}
/**
* Returns a comma separated list of conformance rule IDs, or an empty string if no IDs.
*/
public static String getConformanceRuleIds(Property property) {
Stereotype validationSupport = CDAProfileUtil.getAppliedCDAStereotype(
property, ICDAProfileConstants.PROPERTY_VALIDATION);
return getConformanceRuleIds(property, validationSupport);
}
/**
* Returns a comma separated list of conformance rule IDs, or an empty string if no IDs.
*/
public static String getTerminologyConformanceRuleIds(Property property) {
Stereotype terminologyConstraint = getTerminologyConstraint(property);
return getConformanceRuleIds(property, terminologyConstraint);
}
/**
* Returns a comma separated list of conformance rule IDs, or an empty string if no IDs.
*/
public static String getConformanceRuleIds(Association association) {
Stereotype validationSupport = CDAProfileUtil.getAppliedCDAStereotype(
association, ICDAProfileConstants.ASSOCIATION_VALIDATION);
return getConformanceRuleIds(association, validationSupport);
}
/**
* Returns a comma separated list of conformance rule IDs, or an empty string if no IDs.
*/
public static String getConformanceRuleIds(Element element) {
Stereotype validationSupport = CDAProfileUtil.getAppliedCDAStereotype(element, ICDAProfileConstants.VALIDATION);
return getConformanceRuleIds(element, validationSupport);
}
public static String getConformanceRuleIds(Element element, Stereotype validationSupport) {
StringBuffer ruleIdDisplay = new StringBuffer();
if (validationSupport != null) {
Validation validation = (Validation) element.getStereotypeApplication(validationSupport);
for (String ruleId : validation.getRuleId()) {
if (ruleIdDisplay.length() > 0) {
ruleIdDisplay.append(", ");
}
ruleIdDisplay.append(ruleId);
}
}
return ruleIdDisplay.toString();
}
public static Stereotype getTerminologyConstraint(Element element) {
Stereotype stereotype = CDAProfileUtil.getAppliedCDAStereotype(
element, ITermProfileConstants.CONCEPT_DOMAIN_CONSTRAINT);
if (stereotype == null) {
stereotype = CDAProfileUtil.getAppliedCDAStereotype(element, ITermProfileConstants.CODE_SYSTEM_CONSTRAINT);
}
if (stereotype == null) {
stereotype = CDAProfileUtil.getAppliedCDAStereotype(element, ITermProfileConstants.VALUE_SET_CONSTRAINT);
}
return stereotype;
}
public static boolean hasValidationSupport(Element element) {
Stereotype validationSupport = CDAProfileUtil.getAppliedCDAStereotype(element, ICDAProfileConstants.VALIDATION);
return validationSupport != null;
}
/**
* @deprecated Use {@link #getValidationSeverity(Property, String)} to get the severity for a specific validation stereotype.
* If necessary, this can be the abstract {@link ICDAProfileConstants#VALIDATION Validation} stereotype to get any available
* validation severity.
*/
@Deprecated
public static String getValidationSeverity(Property property) {
return getValidationSeverity(property, ICDAProfileConstants.PROPERTY_VALIDATION);
}
public static String getValidationSeverity(Property property, String validationStereotypeName) {
Stereotype validationStereotype = CDAProfileUtil.getAppliedCDAStereotype(property, validationStereotypeName);
return getValidationSeverity(property, validationStereotype);
}
public static String getValidationSeverity(Element element) {
// use first available validation stereotype
return getValidationSeverity(element, ICDAProfileConstants.VALIDATION);
}
public static String getValidationSeverity(Element element, String validationStereotypeName) {
Stereotype validationStereotype = CDAProfileUtil.getAppliedCDAStereotype(element, validationStereotypeName);
return getValidationSeverity(element, validationStereotype);
}
public static String getValidationSeverity(Element element, Stereotype validationStereotype) {
String severity = null;
if ((validationStereotype != null) && CDAProfileUtil.isValidationStereotype(validationStereotype)) {
Object value = element.getValue(validationStereotype, ICDAProfileConstants.VALIDATION_SEVERITY);
if (value instanceof EnumerationLiteral) {
severity = ((EnumerationLiteral) value).getName();
} else if (value instanceof Enumerator) {
severity = ((Enumerator) value).getName();
}
}
return severity;
}
public static String getValidationKeywordWithPropertyRange(Property property) {
String keyword = getValidationKeyword(property);
return addShallNot(keyword, property);
}
public static String getValidationKeyword(Property property) {
String severity = getValidationSeverity(property, ICDAProfileConstants.PROPERTY_VALIDATION);
if (severity == null) {
// get other validation stereotype, usually for terminology
severity = getValidationSeverity((Element) property);
}
return getValidationKeyword(severity);
}
public static String getValidationKeywordWithPropertyRange(Element element, Property property) {
// use first available validation stereotype
String keyword = getValidationKeyword(element);
return addShallNot(keyword, property);
}
private static String addShallNot(String keyword, Property property) {
if (property.getLower() == 0 && property.getUpper() == 0 &&
("SHALL".equals(keyword) || "SHOULD".equals(keyword))) {
keyword += " NOT";
}
return keyword;
}
public static String getValidationKeyword(Element element) {
// use first available validation stereotype
String severity = getValidationSeverity(element);
return getValidationKeyword(severity);
}
public static String getValidationKeyword(Element element, Stereotype validationStereotype) {
String severity = getValidationSeverity(element, validationStereotype);
return getValidationKeyword(severity);
}
private static String getValidationKeyword(String severity) {
String keyword = null;
if (SEVERITY_INFO.equals(severity)) {
keyword = "MAY";
} else if (SEVERITY_WARNING.equals(severity)) {
keyword = "SHOULD";
} else if (SEVERITY_ERROR.equals(severity)) {
keyword = "SHALL";
}
return keyword;
}
public static void setValidationMessage(Element constrainedElement, String message) {
Stereotype validationSupport = CDAProfileUtil.getAppliedCDAStereotype(
constrainedElement, ICDAProfileConstants.VALIDATION);
if (validationSupport != null) {
constrainedElement.setValue(validationSupport, ICDAProfileConstants.VALIDATION_MESSAGE, message);
}
}
protected static String getLiteralValue(Element element, Stereotype stereotype, String propertyName) {
Object value = element.getValue(stereotype, propertyName);
String name = null;
if (value instanceof EnumerationLiteral) {
name = ((EnumerationLiteral) value).getName();
} else if (value instanceof Enumerator) {
name = ((Enumerator) value).getName();
}
return name;
}
protected static String getLiteralValueLabel(Element element, Stereotype stereotype, String propertyName,
Enumeration umlEnumeration) {
Object value = element.getValue(stereotype, propertyName);
String name = null;
if (value instanceof EnumerationLiteral) {
name = ((EnumerationLiteral) value).getLabel();
} else if (value instanceof Enumerator) {
name = ((Enumerator) value).getName();
if (umlEnumeration != null) {
name = umlEnumeration.getOwnedLiteral(name).getLabel();
}
}
return name;
}
public static String fixNonXMLCharacters(String text) {
if (text == null) {
return null;
}
StringBuffer newText = new StringBuffer();
for (int i = 0; i < text.length(); i++) {
// test for unicode characters from copy/paste of MS Word text
if (text.charAt(i) == '\u201D') {
newText.append("\"");
} else if (text.charAt(i) == '\u201C') {
newText.append("\"");
} else if (text.charAt(i) == '\u2019') {
newText.append("'");
} else if (text.charAt(i) == '\u2018') {
newText.append("'");
} else {
newText.append(text.charAt(i));
}
}
return newText.toString();
}
public static String escapeMarkupCharacters(String text) {
if (text == null) {
return null;
}
text = fixNonXMLCharacters(text);
StringBuffer newText = new StringBuffer();
for (int i = 0; i < text.length(); i++) {
if (text.charAt(i) == '<') {
newText.append("<");
} else if (text.charAt(i) == '>') {
newText.append(">");
} else {
newText.append(text.charAt(i));
}
}
return newText.toString();
}
public static String normalizeCodeName(String name) {
String result = "";
String[] parts = name.split(" ");
for (String part : parts) {
result += part.substring(0, 1).toUpperCase() + part.substring(1);
}
result = UML2Util.getValidJavaIdentifier(result);
return result;
}
private static String mandatoryOrNotMessage(Property curProperty) {
// capture if allows nullFlavor or not
boolean mandatory = CDAProfileUtil.isMandatory(curProperty);
// mandatory implies nullFlavor is NOT allowed ", where the @code "
// non-mandatory implies nullFlavor is allowed ", which "
// return the proper message based on mandatory or not
return mandatory
? ", where the @code "
: ", which ";
}
public static boolean isInlineClass(Class _class) {
Inline inline = CDAProfileUtil.getInline(_class);
if (inline != null) {
return true;
}
if (_class.getOwner() instanceof Class) {
return true;
}
for (Comment comment : _class.getOwnedComments()) {
if (comment.getBody().startsWith("INLINE")) {
return true;
}
}
return false;
}
public static String getInlineFilter(Class inlineClass) {
Inline inline = CDAProfileUtil.getInline(inlineClass);
if (inline != null) {
return inline.getFilter() != null
? inline.getFilter()
: "";
}
String filter = "";
for (Comment comment : inlineClass.getOwnedComments()) {
if (comment.getBody().startsWith("INLINE&")) {
String[] temp = comment.getBody().split("&");
if (temp.length == 2) {
filter = String.format("->select(%s)", temp[1]);
}
break;
}
}
if ("".equals(filter)) {
// search hierarchy
for (Classifier next : inlineClass.getGenerals()) {
if (next instanceof Class) {
filter = getInlineFilter((Class) next);
if (!"".equals(filter)) {
break;
}
}
}
}
return filter;
}
public static boolean isPublishSeperately(Class _class) {
boolean publish = false;
Stereotype stereotype = CDAProfileUtil.getAppliedCDAStereotype(_class, ICDAProfileConstants.INLINE);
if (stereotype != null) {
Boolean result = (Boolean) _class.getValue(stereotype, "publishSeperately");
publish = result.booleanValue();
}
return publish;
}
}
|
package com.raoulvdberge.refinedstorage.apiimpl.network.node;
import com.raoulvdberge.refinedstorage.RS;
import com.raoulvdberge.refinedstorage.RSBlocks;
import com.raoulvdberge.refinedstorage.RSItems;
import com.raoulvdberge.refinedstorage.api.network.INetwork;
import com.raoulvdberge.refinedstorage.api.network.grid.GridType;
import com.raoulvdberge.refinedstorage.api.network.grid.IGrid;
import com.raoulvdberge.refinedstorage.api.network.grid.IGridNetworkAware;
import com.raoulvdberge.refinedstorage.api.network.grid.IGridTab;
import com.raoulvdberge.refinedstorage.api.network.grid.handler.IFluidGridHandler;
import com.raoulvdberge.refinedstorage.api.network.grid.handler.IItemGridHandler;
import com.raoulvdberge.refinedstorage.api.network.item.INetworkItem;
import com.raoulvdberge.refinedstorage.api.network.item.NetworkItemAction;
import com.raoulvdberge.refinedstorage.api.network.security.Permission;
import com.raoulvdberge.refinedstorage.api.storage.IStorageCache;
import com.raoulvdberge.refinedstorage.api.storage.IStorageCacheListener;
import com.raoulvdberge.refinedstorage.api.util.IComparer;
import com.raoulvdberge.refinedstorage.api.util.IFilter;
import com.raoulvdberge.refinedstorage.apiimpl.API;
import com.raoulvdberge.refinedstorage.apiimpl.storage.StorageCacheListenerGridFluid;
import com.raoulvdberge.refinedstorage.apiimpl.storage.StorageCacheListenerGridItem;
import com.raoulvdberge.refinedstorage.block.BlockGrid;
import com.raoulvdberge.refinedstorage.inventory.ItemHandlerBase;
import com.raoulvdberge.refinedstorage.inventory.ItemHandlerFilter;
import com.raoulvdberge.refinedstorage.inventory.ItemHandlerListenerNetworkNode;
import com.raoulvdberge.refinedstorage.inventory.ItemValidatorBasic;
import com.raoulvdberge.refinedstorage.item.ItemPattern;
import com.raoulvdberge.refinedstorage.tile.data.TileDataManager;
import com.raoulvdberge.refinedstorage.tile.grid.TileGrid;
import com.raoulvdberge.refinedstorage.util.StackUtils;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.inventory.*;
import net.minecraft.item.ItemStack;
import net.minecraft.item.crafting.CraftingManager;
import net.minecraft.item.crafting.IRecipe;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.util.NonNullList;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.World;
import net.minecraftforge.fml.common.FMLCommonHandler;
import net.minecraftforge.items.IItemHandler;
import net.minecraftforge.items.IItemHandlerModifiable;
import net.minecraftforge.items.ItemHandlerHelper;
import net.minecraftforge.items.wrapper.CombinedInvWrapper;
import net.minecraftforge.items.wrapper.InvWrapper;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import java.util.ArrayList;
import java.util.List;
public class NetworkNodeGrid extends NetworkNode implements IGridNetworkAware {
public static final String ID = "grid";
public static final String NBT_VIEW_TYPE = "ViewType";
public static final String NBT_SORTING_DIRECTION = "SortingDirection";
public static final String NBT_SORTING_TYPE = "SortingType";
public static final String NBT_SEARCH_BOX_MODE = "SearchBoxMode";
public static final String NBT_OREDICT_PATTERN = "OredictPattern";
public static final String NBT_TAB_SELECTED = "TabSelected";
public static final String NBT_TAB_PAGE = "TabPage";
public static final String NBT_SIZE = "Size";
public static final String NBT_PROCESSING_PATTERN = "ProcessingPattern";
private Container craftingContainer = new Container() {
@Override
public boolean canInteractWith(EntityPlayer player) {
return false;
}
@Override
public void onCraftMatrixChanged(IInventory inventory) {
onCraftingMatrixChanged();
}
};
private IRecipe currentRecipe;
private InventoryCrafting matrix = new InventoryCrafting(craftingContainer, 3, 3);
private InventoryCraftResult result = new InventoryCraftResult();
private ItemHandlerBase matrixProcessing = new ItemHandlerBase(9 * 2, new ItemHandlerListenerNetworkNode(this));
private ItemHandlerBase patterns = new ItemHandlerBase(2, new ItemHandlerListenerNetworkNode(this), new ItemValidatorBasic(RSItems.PATTERN)) {
@Override
protected void onContentsChanged(int slot) {
super.onContentsChanged(slot);
ItemStack pattern = getStackInSlot(slot);
if (slot == 1 && !pattern.isEmpty()) {
boolean isPatternProcessing = ItemPattern.isProcessing(pattern);
if (isPatternProcessing && isProcessingPattern()) {
for (int i = 0; i < 9; ++i) {
matrixProcessing.setStackInSlot(i, StackUtils.nullToEmpty(ItemPattern.getInputSlot(pattern, i)));
}
for (int i = 0; i < 9; ++i) {
matrixProcessing.setStackInSlot(9 + i, StackUtils.nullToEmpty(ItemPattern.getOutputSlot(pattern, i)));
}
} else if (!isPatternProcessing && !isProcessingPattern()) {
for (int i = 0; i < 9; ++i) {
matrix.setInventorySlotContents(i, StackUtils.nullToEmpty(ItemPattern.getInputSlot(pattern, i)));
}
}
}
}
@Override
public int getSlotLimit(int slot) {
return slot == 1 ? 1 : super.getSlotLimit(slot);
}
@Nonnull
@Override
public ItemStack insertItem(int slot, @Nonnull ItemStack stack, boolean simulate) {
// Allow in slot 0
// Disallow in slot 1
// Only allow in slot 1 when it isn't a blank pattern
// This makes it so that written patterns can be re-inserted in slot 1 to be overwritten again
// This makes it so that blank patterns can't be inserted in slot 1 through hoppers.
if (slot == 0 || stack.getTagCompound() != null) {
return super.insertItem(slot, stack, simulate);
}
return stack;
}
};
private List<IFilter> filters = new ArrayList<>();
private List<IGridTab> tabs = new ArrayList<>();
private ItemHandlerFilter filter = new ItemHandlerFilter(filters, tabs, new ItemHandlerListenerNetworkNode(this));
private GridType type;
private int viewType = VIEW_TYPE_NORMAL;
private int sortingDirection = SORTING_DIRECTION_DESCENDING;
private int sortingType = SORTING_TYPE_QUANTITY;
private int searchBoxMode = SEARCH_BOX_MODE_NORMAL;
private int size = SIZE_STRETCH;
private int tabSelected = -1;
private int tabPage = 0;
private boolean oredictPattern = false;
private boolean processingPattern = false;
public NetworkNodeGrid(World world, BlockPos pos) {
super(world, pos);
}
@Override
public int getEnergyUsage() {
switch (getType()) {
case NORMAL:
return RS.INSTANCE.config.gridUsage;
case CRAFTING:
return RS.INSTANCE.config.craftingGridUsage;
case PATTERN:
return RS.INSTANCE.config.patternGridUsage;
case FLUID:
return RS.INSTANCE.config.fluidGridUsage;
default:
return 0;
}
}
public void setViewType(int viewType) {
this.viewType = viewType;
}
public void setSortingDirection(int sortingDirection) {
this.sortingDirection = sortingDirection;
}
public void setSortingType(int sortingType) {
this.sortingType = sortingType;
}
public void setSearchBoxMode(int searchBoxMode) {
this.searchBoxMode = searchBoxMode;
}
public void setTabSelected(int tabSelected) {
this.tabSelected = tabSelected;
}
public void setTabPage(int page) {
this.tabPage = page;
}
public void setSize(int size) {
this.size = size;
}
public boolean isOredictPattern() {
return oredictPattern;
}
public void setOredictPattern(boolean oredictPattern) {
this.oredictPattern = oredictPattern;
}
public boolean isProcessingPattern() {
return world.isRemote ? TileGrid.PROCESSING_PATTERN.getValue() : processingPattern;
}
public void setProcessingPattern(boolean processingPattern) {
this.processingPattern = processingPattern;
}
public GridType getType() {
if (type == null && world.getBlockState(pos).getBlock() == RSBlocks.GRID) {
type = (GridType) world.getBlockState(pos).getValue(BlockGrid.TYPE);
}
return type == null ? GridType.NORMAL : type;
}
@Override
public IStorageCacheListener createListener(EntityPlayerMP player) {
return getType() == GridType.FLUID ? new StorageCacheListenerGridFluid(player, network) : new StorageCacheListenerGridItem(player, network);
}
@Nullable
@Override
public IStorageCache getStorageCache() {
return network != null ? (getType() == GridType.FLUID ? network.getFluidStorageCache() : network.getItemStorageCache()) : null;
}
@Nullable
@Override
public IItemGridHandler getItemHandler() {
return network != null ? network.getItemGridHandler() : null;
}
@Nullable
@Override
public IFluidGridHandler getFluidHandler() {
return network != null ? network.getFluidGridHandler() : null;
}
@Override
public String getGuiTitle() {
GridType type = getType();
switch (type) {
case CRAFTING:
return "gui.refinedstorage:crafting_grid";
case PATTERN:
return "gui.refinedstorage:pattern_grid";
case FLUID:
return "gui.refinedstorage:fluid_grid";
default:
return "gui.refinedstorage:grid";
}
}
public IItemHandler getPatterns() {
return patterns;
}
@Override
public IItemHandlerModifiable getFilter() {
return filter;
}
@Override
public List<IFilter> getFilters() {
return filters;
}
@Override
public List<IGridTab> getTabs() {
return tabs;
}
@Override
public InventoryCrafting getCraftingMatrix() {
return matrix;
}
@Override
public InventoryCraftResult getCraftingResult() {
return result;
}
public ItemHandlerBase getProcessingMatrix() {
return matrixProcessing;
}
@Override
public void onCraftingMatrixChanged() {
if (currentRecipe == null || !currentRecipe.matches(matrix, world)) {
currentRecipe = CraftingManager.findMatchingRecipe(matrix, world);
}
if (currentRecipe == null) {
result.setInventorySlotContents(0, ItemStack.EMPTY);
} else {
result.setInventorySlotContents(0, currentRecipe.getCraftingResult(matrix));
}
markDirty();
}
@Override
public void onRecipeTransfer(EntityPlayer player, ItemStack[][] recipe) {
onRecipeTransfer(this, player, recipe);
}
public static void onRecipeTransfer(IGridNetworkAware grid, EntityPlayer player, ItemStack[][] recipe) {
INetwork network = grid.getNetwork();
if (network != null && grid.getType() == GridType.CRAFTING && !network.getSecurityManager().hasPermission(Permission.EXTRACT, player)) {
return;
}
// First try to empty the crafting matrix
for (int i = 0; i < grid.getCraftingMatrix().getSizeInventory(); ++i) {
ItemStack slot = grid.getCraftingMatrix().getStackInSlot(i);
if (!slot.isEmpty()) {
// Only if we are a crafting grid. Pattern grids can just be emptied.
if (grid.getType() == GridType.CRAFTING) {
// If we are connected, try to insert into network. If it fails, stop.
if (network != null) {
if (network.insertItem(slot, slot.getCount(), true) != null) {
return;
} else {
network.insertItem(slot, slot.getCount(), false);
}
} else {
// If we aren't connected, try to insert into player inventory. If it fails, stop.
if (!player.inventory.addItemStackToInventory(slot.copy())) {
return;
}
}
}
grid.getCraftingMatrix().setInventorySlotContents(i, ItemStack.EMPTY);
}
}
// Now let's fill the matrix
for (int i = 0; i < grid.getCraftingMatrix().getSizeInventory(); ++i) {
if (recipe[i] != null) {
ItemStack[] possibilities = recipe[i];
// If we are a crafting grid
if (grid.getType() == GridType.CRAFTING) {
boolean found = false;
// If we are connected, first try to get the possibilities from the network
if (network != null) {
for (ItemStack possibility : possibilities) {
ItemStack took = network.extractItem(possibility, 1, IComparer.COMPARE_NBT | (possibility.getItem().isDamageable() ? 0 : IComparer.COMPARE_DAMAGE), false);
if (took != null) {
grid.getCraftingMatrix().setInventorySlotContents(i, StackUtils.nullToEmpty(took));
found = true;
break;
}
}
}
// If we haven't found anything in the network (or we are disconnected), go look in the player inventory
if (!found) {
for (ItemStack possibility : possibilities) {
for (int j = 0; j < player.inventory.getSizeInventory(); ++j) {
if (API.instance().getComparer().isEqual(possibility, player.inventory.getStackInSlot(j), IComparer.COMPARE_NBT | (possibility.getItem().isDamageable() ? 0 : IComparer.COMPARE_DAMAGE))) {
grid.getCraftingMatrix().setInventorySlotContents(i, ItemHandlerHelper.copyStackWithSize(player.inventory.getStackInSlot(j), 1));
player.inventory.decrStackSize(j, 1);
found = true;
break;
}
}
if (found) {
break;
}
}
}
} else if (grid.getType() == GridType.PATTERN) {
// If we are a pattern grid we can just set the slot
grid.getCraftingMatrix().setInventorySlotContents(i, possibilities.length == 0 ? ItemStack.EMPTY : possibilities[0]);
}
}
}
}
public void clearMatrix() {
for (int i = 0; i < matrixProcessing.getSlots(); ++i) {
matrixProcessing.setStackInSlot(i, ItemStack.EMPTY);
}
for (int i = 0; i < matrix.getSizeInventory(); ++i) {
matrix.setInventorySlotContents(i, ItemStack.EMPTY);
}
}
@Override
public void onClosed(EntityPlayer player) {
// NO OP
}
@Override
public void onCrafted(EntityPlayer player) {
onCrafted(this, world, player);
}
public static void onCrafted(IGridNetworkAware grid, World world, EntityPlayer player) {
NonNullList<ItemStack> remainder = CraftingManager.getRemainingItems(grid.getCraftingMatrix(), world);
INetwork network = grid.getNetwork();
InventoryCrafting matrix = grid.getCraftingMatrix();
for (int i = 0; i < grid.getCraftingMatrix().getSizeInventory(); ++i) {
ItemStack slot = matrix.getStackInSlot(i);
if (i < remainder.size() && !remainder.get(i).isEmpty()) {
// If there is no space for the remainder, dump it in the player inventory
if (!slot.isEmpty() && slot.getCount() > 1) {
if (!player.inventory.addItemStackToInventory(remainder.get(i).copy())) {
ItemStack remainderStack = network == null ? remainder.get(i).copy() : network.insertItem(remainder.get(i).copy(), remainder.get(i).getCount(), false);
if (remainderStack != null) {
InventoryHelper.spawnItemStack(player.getEntityWorld(), player.getPosition().getX(), player.getPosition().getY(), player.getPosition().getZ(), remainderStack);
}
}
matrix.decrStackSize(i, 1);
} else {
matrix.setInventorySlotContents(i, remainder.get(i).copy());
}
} else if (!slot.isEmpty()) {
if (slot.getCount() == 1 && network != null) {
matrix.setInventorySlotContents(i, StackUtils.nullToEmpty(network.extractItem(slot, 1, false)));
} else {
matrix.decrStackSize(i, 1);
}
}
}
grid.onCraftingMatrixChanged();
if (network != null) {
INetworkItem networkItem = network.getNetworkItemHandler().getItem(player);
if (networkItem != null) {
networkItem.onAction(NetworkItemAction.ITEM_CRAFTED);
}
}
}
@Override
public void onCraftedShift(EntityPlayer player) {
onCraftedShift(this, player);
}
public static void onCraftedShift(IGridNetworkAware grid, EntityPlayer player) {
List<ItemStack> craftedItemsList = new ArrayList<>();
int craftedItems = 0;
ItemStack crafted = grid.getCraftingResult().getStackInSlot(0);
while (true) {
grid.onCrafted(player);
craftedItemsList.add(crafted.copy());
craftedItems += crafted.getCount();
if (!API.instance().getComparer().isEqual(crafted, grid.getCraftingResult().getStackInSlot(0)) || craftedItems + crafted.getCount() > crafted.getMaxStackSize()) {
break;
}
}
INetwork network = grid.getNetwork();
for (ItemStack craftedItem : craftedItemsList) {
if (!player.inventory.addItemStackToInventory(craftedItem.copy())) {
ItemStack remainder = network == null ? craftedItem : network.insertItem(craftedItem, craftedItem.getCount(), false);
if (remainder != null) {
InventoryHelper.spawnItemStack(player.getEntityWorld(), player.getPosition().getX(), player.getPosition().getY(), player.getPosition().getZ(), remainder);
}
}
}
FMLCommonHandler.instance().firePlayerCraftingEvent(player, ItemHandlerHelper.copyStackWithSize(crafted, craftedItems), grid.getCraftingMatrix());
}
public void onCreatePattern() {
if (canCreatePattern()) {
if (patterns.getStackInSlot(1).isEmpty()) {
patterns.extractItem(0, 1, false);
}
ItemStack pattern = new ItemStack(RSItems.PATTERN);
ItemPattern.setOredict(pattern, oredictPattern);
ItemPattern.setProcessing(pattern, processingPattern);
if (processingPattern) {
for (int i = 0; i < 18; ++i) {
if (!matrixProcessing.getStackInSlot(i).isEmpty()) {
if (i >= 9) {
ItemPattern.setOutputSlot(pattern, i - 9, matrixProcessing.getStackInSlot(i));
} else {
ItemPattern.setInputSlot(pattern, i, matrixProcessing.getStackInSlot(i));
}
}
}
} else {
for (int i = 0; i < 9; ++i) {
ItemStack ingredient = matrix.getStackInSlot(i);
if (!ingredient.isEmpty()) {
ItemPattern.setInputSlot(pattern, i, ingredient);
}
}
}
patterns.setStackInSlot(1, pattern);
}
}
private boolean isPatternAvailable() {
return !(patterns.getStackInSlot(0).isEmpty() && patterns.getStackInSlot(1).isEmpty());
}
public boolean canCreatePattern() {
if (!isPatternAvailable()) {
return false;
}
if (isProcessingPattern()) {
int inputsFilled = 0;
int outputsFilled = 0;
for (int i = 0; i < 9; ++i) {
if (!matrixProcessing.getStackInSlot(i).isEmpty()) {
inputsFilled++;
}
}
for (int i = 9; i < 18; ++i) {
if (!matrixProcessing.getStackInSlot(i).isEmpty()) {
outputsFilled++;
}
}
return inputsFilled > 0 && outputsFilled > 0;
} else {
return !result.getStackInSlot(0).isEmpty() && isPatternAvailable();
}
}
@Override
public int getViewType() {
return world.isRemote ? TileGrid.VIEW_TYPE.getValue() : viewType;
}
@Override
public int getSortingDirection() {
return world.isRemote ? TileGrid.SORTING_DIRECTION.getValue() : sortingDirection;
}
@Override
public int getSortingType() {
return world.isRemote ? TileGrid.SORTING_TYPE.getValue() : sortingType;
}
@Override
public int getSearchBoxMode() {
return world.isRemote ? TileGrid.SEARCH_BOX_MODE.getValue() : searchBoxMode;
}
@Override
public int getSize() {
return world.isRemote ? TileGrid.SIZE.getValue() : size;
}
@Override
public int getTabSelected() {
return world.isRemote ? TileGrid.TAB_SELECTED.getValue() : tabSelected;
}
@Override
public int getTabPage() {
return world.isRemote ? TileGrid.TAB_PAGE.getValue() : Math.min(tabPage, getTotalTabPages());
}
@Override
public int getTotalTabPages() {
return (int) Math.floor((float) Math.max(0, tabs.size() - 1) / (float) IGrid.TABS_PER_PAGE);
}
@Override
public void onViewTypeChanged(int type) {
TileDataManager.setParameter(TileGrid.VIEW_TYPE, type);
}
@Override
public void onSortingTypeChanged(int type) {
TileDataManager.setParameter(TileGrid.SORTING_TYPE, type);
}
@Override
public void onSortingDirectionChanged(int direction) {
TileDataManager.setParameter(TileGrid.SORTING_DIRECTION, direction);
}
@Override
public void onSearchBoxModeChanged(int searchBoxMode) {
TileDataManager.setParameter(TileGrid.SEARCH_BOX_MODE, searchBoxMode);
}
@Override
public void onSizeChanged(int size) {
TileDataManager.setParameter(TileGrid.SIZE, size);
}
@Override
public void onTabSelectionChanged(int tab) {
TileDataManager.setParameter(TileGrid.TAB_SELECTED, tab);
}
@Override
public void onTabPageChanged(int page) {
if (page >= 0 && page <= getTotalTabPages()) {
TileDataManager.setParameter(TileGrid.TAB_PAGE, page);
}
}
@Override
public boolean hasConnectivityState() {
return true;
}
@Override
public void read(NBTTagCompound tag) {
super.read(tag);
StackUtils.readItems(matrix, 0, tag);
StackUtils.readItems(patterns, 1, tag);
StackUtils.readItems(filter, 2, tag);
StackUtils.readItems(matrixProcessing, 3, tag);
if (tag.hasKey(NBT_TAB_SELECTED)) {
tabSelected = tag.getInteger(NBT_TAB_SELECTED);
}
if (tag.hasKey(NBT_TAB_PAGE)) {
tabPage = tag.getInteger(NBT_TAB_PAGE);
}
}
@Override
public String getId() {
return ID;
}
@Override
public NBTTagCompound write(NBTTagCompound tag) {
super.write(tag);
StackUtils.writeItems(matrix, 0, tag);
StackUtils.writeItems(patterns, 1, tag);
StackUtils.writeItems(filter, 2, tag);
StackUtils.writeItems(matrixProcessing, 3, tag);
tag.setInteger(NBT_TAB_SELECTED, tabSelected);
tag.setInteger(NBT_TAB_PAGE, tabPage);
return tag;
}
@Override
public NBTTagCompound writeConfiguration(NBTTagCompound tag) {
super.writeConfiguration(tag);
tag.setInteger(NBT_VIEW_TYPE, viewType);
tag.setInteger(NBT_SORTING_DIRECTION, sortingDirection);
tag.setInteger(NBT_SORTING_TYPE, sortingType);
tag.setInteger(NBT_SEARCH_BOX_MODE, searchBoxMode);
tag.setInteger(NBT_SIZE, size);
tag.setBoolean(NBT_OREDICT_PATTERN, oredictPattern);
tag.setBoolean(NBT_PROCESSING_PATTERN, processingPattern);
return tag;
}
@Override
public void readConfiguration(NBTTagCompound tag) {
super.readConfiguration(tag);
if (tag.hasKey(NBT_VIEW_TYPE)) {
viewType = tag.getInteger(NBT_VIEW_TYPE);
}
if (tag.hasKey(NBT_SORTING_DIRECTION)) {
sortingDirection = tag.getInteger(NBT_SORTING_DIRECTION);
}
if (tag.hasKey(NBT_SORTING_TYPE)) {
sortingType = tag.getInteger(NBT_SORTING_TYPE);
}
if (tag.hasKey(NBT_SEARCH_BOX_MODE)) {
searchBoxMode = tag.getInteger(NBT_SEARCH_BOX_MODE);
}
if (tag.hasKey(NBT_SIZE)) {
size = tag.getInteger(NBT_SIZE);
}
if (tag.hasKey(NBT_OREDICT_PATTERN)) {
oredictPattern = tag.getBoolean(NBT_OREDICT_PATTERN);
}
if (tag.hasKey(NBT_PROCESSING_PATTERN)) {
processingPattern = tag.getBoolean(NBT_PROCESSING_PATTERN);
}
}
@Override
public IItemHandler getDrops() {
switch (getType()) {
case CRAFTING:
return new CombinedInvWrapper(filter, new InvWrapper(matrix));
case PATTERN:
return new CombinedInvWrapper(filter, patterns);
default:
return new CombinedInvWrapper(filter);
}
}
}
|
package io.cattle.platform.configitem.context.dao.impl;
import static io.cattle.platform.core.model.tables.HostIpAddressMapTable.*;
import static io.cattle.platform.core.model.tables.HostTable.*;
import static io.cattle.platform.core.model.tables.InstanceHostMapTable.*;
import static io.cattle.platform.core.model.tables.InstanceTable.*;
import static io.cattle.platform.core.model.tables.IpAddressNicMapTable.*;
import static io.cattle.platform.core.model.tables.IpAddressTable.*;
import static io.cattle.platform.core.model.tables.NetworkTable.*;
import static io.cattle.platform.core.model.tables.NicTable.*;
import static io.cattle.platform.core.model.tables.ServiceExposeMapTable.*;
import io.cattle.platform.configitem.context.dao.DnsInfoDao;
import io.cattle.platform.configitem.context.dao.MetaDataInfoDao;
import io.cattle.platform.configitem.context.data.metadata.common.ContainerMetaData;
import io.cattle.platform.configitem.context.data.metadata.common.HostMetaData;
import io.cattle.platform.configitem.context.data.metadata.common.NetworkMetaData;
import io.cattle.platform.core.constants.CommonStatesConstants;
import io.cattle.platform.core.constants.InstanceConstants;
import io.cattle.platform.core.constants.IpAddressConstants;
import io.cattle.platform.core.constants.ServiceConstants;
import io.cattle.platform.core.dao.InstanceDao;
import io.cattle.platform.core.model.Host;
import io.cattle.platform.core.model.Instance;
import io.cattle.platform.core.model.IpAddress;
import io.cattle.platform.core.model.Network;
import io.cattle.platform.core.model.Nic;
import io.cattle.platform.core.model.ServiceExposeMap;
import io.cattle.platform.core.model.tables.HostTable;
import io.cattle.platform.core.model.tables.InstanceTable;
import io.cattle.platform.core.model.tables.IpAddressTable;
import io.cattle.platform.core.model.tables.NetworkTable;
import io.cattle.platform.core.model.tables.NicTable;
import io.cattle.platform.core.model.tables.ServiceExposeMapTable;
import io.cattle.platform.db.jooq.dao.impl.AbstractJooqDao;
import io.cattle.platform.db.jooq.mapper.MultiRecordMapper;
import io.cattle.platform.object.util.DataAccessor;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.inject.Inject;
import org.jooq.JoinType;
import org.jooq.Record1;
import org.jooq.RecordHandler;
public class MetaDataInfoDaoImpl extends AbstractJooqDao implements MetaDataInfoDao {
@Inject
DnsInfoDao dnsInfoDao;
@Inject
InstanceDao instanceDao;
@Override
public List<ContainerMetaData> getContainersData(long accountId) {
final Map<Long, IpAddress> instanceIdToHostIpMap = dnsInfoDao
.getInstanceWithHostNetworkingToIpMap(accountId);
final Map<Long, HostMetaData> hostIdToHostMetadata = getHostIdToHostMetadata(accountId);
MultiRecordMapper<ContainerMetaData> mapper = new MultiRecordMapper<ContainerMetaData>() {
@Override
protected ContainerMetaData map(List<Object> input) {
ContainerMetaData data = new ContainerMetaData();
Instance instance = (Instance) input.get(0);
instance.setData(instanceDao.getCacheInstanceData(instance.getId()));
ServiceExposeMap serviceMap = input.get(1) != null ? (ServiceExposeMap) input.get(1) : null;
String serviceIndex = DataAccessor.fieldString(instance,
InstanceConstants.FIELD_SERVICE_INSTANCE_SERVICE_INDEX);
Host host = null;
if (input.get(2) != null) {
host = (Host) input.get(2);
}
String primaryIp = null;
if (input.get(3) != null) {
primaryIp = ((IpAddress) input.get(3)).getAddress();
}
if (instanceIdToHostIpMap != null && instanceIdToHostIpMap.containsKey(instance.getId())) {
data.setIp(instanceIdToHostIpMap.get(instance.getId()).getAddress());
} else {
data.setIp(primaryIp);
}
if (host != null) {
HostMetaData hostMetaData = hostIdToHostMetadata.get(host.getId());
data.setInstanceAndHostMetadata(instance, hostMetaData);
}
data.setExposeMap(serviceMap);
data.setService_index(serviceIndex);
Nic nic = null;
if (input.get(4) != null) {
nic = (Nic) input.get(4);
data.setNicInformation(nic);
}
Network ntwk = null;
if (input.get(5) != null) {
ntwk = (Network) input.get(5);
data.setNetwork_uuid(ntwk.getUuid());
}
return data;
}
};
InstanceTable instance = mapper.add(INSTANCE, INSTANCE.UUID, INSTANCE.NAME, INSTANCE.CREATE_INDEX, INSTANCE.HEALTH_STATE,
INSTANCE.START_COUNT, INSTANCE.STATE, INSTANCE.EXTERNAL_ID, INSTANCE.MEMORY_RESERVATION, INSTANCE.MILLI_CPU_RESERVATION);
ServiceExposeMapTable exposeMap = mapper.add(SERVICE_EXPOSE_MAP, SERVICE_EXPOSE_MAP.SERVICE_ID,
SERVICE_EXPOSE_MAP.DNS_PREFIX, SERVICE_EXPOSE_MAP.UPGRADE);
HostTable host = mapper.add(HOST, HOST.ID);
IpAddressTable instanceIpAddress = mapper.add(IP_ADDRESS, IP_ADDRESS.ADDRESS);
NicTable nic = mapper.add(NIC, NIC.ID, NIC.INSTANCE_ID, NIC.MAC_ADDRESS);
NetworkTable ntwk = mapper.add(NETWORK, NETWORK.UUID);
return create()
.select(mapper.fields())
.from(instance)
.join(INSTANCE_HOST_MAP)
.on(instance.ID.eq(INSTANCE_HOST_MAP.INSTANCE_ID))
.join(host)
.on(host.ID.eq(INSTANCE_HOST_MAP.HOST_ID))
.join(exposeMap, JoinType.LEFT_OUTER_JOIN)
.on(exposeMap.INSTANCE_ID.eq(instance.ID))
.join(nic)
.on(nic.INSTANCE_ID.eq(INSTANCE_HOST_MAP.INSTANCE_ID))
.join(IP_ADDRESS_NIC_MAP)
.on(IP_ADDRESS_NIC_MAP.NIC_ID.eq(nic.ID))
.join(instanceIpAddress)
.on(instanceIpAddress.ID.eq(IP_ADDRESS_NIC_MAP.IP_ADDRESS_ID))
.join(ntwk)
.on(nic.NETWORK_ID.eq(ntwk.ID))
.where(instance.ACCOUNT_ID.eq(accountId))
.and(instance.REMOVED.isNull())
.and(instance.STATE.notIn(CommonStatesConstants.REMOVING, CommonStatesConstants.REMOVED))
.and(exposeMap.REMOVED.isNull())
.and(instanceIpAddress.ROLE.eq(IpAddressConstants.ROLE_PRIMARY))
.and(ntwk.REMOVED.isNull())
.and((host.REMOVED.isNull()))
.and(exposeMap.STATE.isNull().or(
exposeMap.STATE.notIn(CommonStatesConstants.REMOVING, CommonStatesConstants.REMOVED)))
.and(exposeMap.UPGRADE.isNull().or(exposeMap.UPGRADE.eq(false)))
.fetch().map(mapper);
}
@Override
public List<String> getPrimaryIpsOnInstanceHost(final long hostId) {
final List<String> ips = new ArrayList<>();
create().select(IP_ADDRESS.ADDRESS)
.from(IP_ADDRESS)
.join(IP_ADDRESS_NIC_MAP)
.on(IP_ADDRESS.ID.eq(IP_ADDRESS_NIC_MAP.IP_ADDRESS_ID))
.join(NIC)
.on(NIC.ID.eq(IP_ADDRESS_NIC_MAP.NIC_ID))
.join(INSTANCE_HOST_MAP)
.on(INSTANCE_HOST_MAP.INSTANCE_ID.eq(NIC.INSTANCE_ID))
.where(INSTANCE_HOST_MAP.HOST_ID.eq(hostId)
.and(NIC.REMOVED.isNull())
.and(IP_ADDRESS_NIC_MAP.REMOVED.isNull())
.and(IP_ADDRESS.REMOVED.isNull())
.and(IP_ADDRESS.ROLE.eq(IpAddressConstants.ROLE_PRIMARY))
)
.fetchInto(new RecordHandler<Record1<String>>() {
@Override
public void next(Record1<String> record) {
ips.add(record.value1());
}
});
return ips;
}
@Override
public Map<Long, HostMetaData> getHostIdToHostMetadata(long accountId) {
Map<Long, HostMetaData> toReturn = new HashMap<>();
List<HostMetaData> hosts = getAllInstanceHostMetaData(accountId);
for (HostMetaData host : hosts) {
toReturn.put(host.getHostId(), host);
}
return toReturn;
}
protected List<HostMetaData> getAllInstanceHostMetaData(long accountId) {
MultiRecordMapper<HostMetaData> mapper = new MultiRecordMapper<HostMetaData>() {
@Override
protected HostMetaData map(List<Object> input) {
Host host = (Host)input.get(0);
IpAddress hostIp = (IpAddress)input.get(1);
HostMetaData data = new HostMetaData(hostIp.getAddress(), host);
return data;
}
};
HostTable host = mapper.add(HOST);
IpAddressTable hostIpAddress = mapper.add(IP_ADDRESS);
return create()
.select(mapper.fields())
.from(hostIpAddress)
.join(HOST_IP_ADDRESS_MAP)
.on(HOST_IP_ADDRESS_MAP.IP_ADDRESS_ID.eq(hostIpAddress.ID))
.join(host)
.on(host.ID.eq(HOST_IP_ADDRESS_MAP.HOST_ID))
.where(host.REMOVED.isNull())
.and(host.STATE.notIn(CommonStatesConstants.REMOVING, CommonStatesConstants.REMOVED))
.and(hostIpAddress.REMOVED.isNull())
.and(host.ACCOUNT_ID.eq(accountId))
.fetch().map(mapper);
}
@Override
public List<HostMetaData> getInstanceHostMetaData(long accountId, long instanceId) {
MultiRecordMapper<HostMetaData> mapper = new MultiRecordMapper<HostMetaData>() {
@Override
protected HostMetaData map(List<Object> input) {
Host host = (Host) input.get(0);
IpAddress hostIp = (IpAddress) input.get(1);
HostMetaData data = new HostMetaData(hostIp.getAddress(), host);
return data;
}
};
HostTable host = mapper.add(HOST);
IpAddressTable hostIpAddress = mapper.add(IP_ADDRESS);
return create()
.select(mapper.fields())
.from(hostIpAddress)
.join(HOST_IP_ADDRESS_MAP)
.on(HOST_IP_ADDRESS_MAP.IP_ADDRESS_ID.eq(hostIpAddress.ID))
.join(host)
.on(host.ID.eq(HOST_IP_ADDRESS_MAP.HOST_ID))
.join(INSTANCE_HOST_MAP)
.on(host.ID.eq(INSTANCE_HOST_MAP.HOST_ID))
.where(host.REMOVED.isNull())
.and(host.STATE.notIn(CommonStatesConstants.REMOVING, CommonStatesConstants.REMOVED))
.and(INSTANCE_HOST_MAP.INSTANCE_ID.eq(instanceId))
.and(hostIpAddress.REMOVED.isNull())
.and(host.ACCOUNT_ID.eq(accountId))
.fetch().map(mapper);
}
@Override
public List<NetworkMetaData> getNetworksMetaData(long accountId) {
MultiRecordMapper<NetworkMetaData> mapper = new MultiRecordMapper<NetworkMetaData>() {
@Override
protected NetworkMetaData map(List<Object> input) {
Network ntwk = (Network) input.get(0);
Map<String, Object> meta = DataAccessor.fieldMap(ntwk, ServiceConstants.FIELD_METADATA);
NetworkMetaData data = new NetworkMetaData(ntwk.getName(), ntwk.getUuid(), meta);
return data;
}
};
NetworkTable ntwk = mapper.add(NETWORK, NETWORK.NAME, NETWORK.UUID, NETWORK.DATA);
return create()
.select(mapper.fields())
.from(ntwk)
.where(ntwk.REMOVED.isNull())
.and(ntwk.ACCOUNT_ID.eq(accountId))
.fetch().map(mapper);
}
}
|
package com.royalrangers.controller.achievement;
import com.dropbox.core.DbxException;
import com.royalrangers.dto.ResponseResult;
import com.royalrangers.dto.achievement.AchievementRequestDto;
import com.royalrangers.enums.ImageType;
import com.royalrangers.service.DropboxService;
import com.royalrangers.service.achievement.QuarterAchievementService;
import com.royalrangers.utils.ResponseBuilder;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
@Slf4j
@RestController
@RequestMapping("/achievements/quarter")
public class QuarterAchievementController {
@Autowired
private QuarterAchievementService quarterAchievementService;
@Autowired
private DropboxService dropboxService;
@GetMapping
@ApiOperation(value = "Get all quarter achievements")
public ResponseResult getAllQuarterAchievement() {
try {
return ResponseBuilder.success(quarterAchievementService.getAllQuarterAchievement());
} catch (Exception ex) {
log.error(ex.getMessage());
return ResponseBuilder.fail("Failed added QuarterAchievement");
}
}
@ApiOperation(value = "Add quarter achievement related to year achievement (upLevelId)")
@PostMapping
public ResponseResult addQuarterAchievement(@RequestBody AchievementRequestDto params) {
try {
quarterAchievementService.addQuarterAchievement(params);
return ResponseBuilder.success("Adding QuarterAchievement was a success");
} catch (Exception ex) {
log.error(ex.getMessage());
return ResponseBuilder.fail("Failed added QuarterAchievement");
}
}
@GetMapping("/{quarterId}")
@ApiOperation(value = "Get quarter achievement by id")
public ResponseResult getQuarterAchievementById(@PathVariable Long quarterId) {
try {
return ResponseBuilder.success(quarterAchievementService.getQuarterAchievementById(quarterId));
} catch (Exception ex) {
log.error(ex.getMessage());
return ResponseBuilder.fail("Failed get QuarterAchievement by id");
}
}
@DeleteMapping("/{quarterId}")
@ApiOperation(value = "Delete quarter achievement by id")
public ResponseResult deleteQuarterAchievement(@PathVariable Long quarterId) {
try {
quarterAchievementService.deleteQuarterAchievement(quarterId);
return ResponseBuilder.success("Delete QuarterAchievement was a success");
} catch (Exception ex) {
log.error(ex.getMessage());
return ResponseBuilder.fail("Failed deleted QuarterAchievement");
}
}
@PutMapping("/{quarterId}")
@ApiOperation(value = "Update quarter achievement by id")
public ResponseResult editQuarterAchievement(@RequestBody AchievementRequestDto params, @PathVariable Long quarterId) {
try {
return ResponseBuilder.success(quarterAchievementService.editQuarterAchievement(params, quarterId));
} catch (Exception ex) {
log.error(ex.getMessage());
return ResponseBuilder.fail("Failed edit QuarterAchievement");
}
}
@PostMapping("/logo")
@ApiOperation(value = "Upload and set quarter achievement logo")
public ResponseResult uploadLogo(@RequestParam("quarterId") Long quarterId, @RequestParam("file") MultipartFile file) {
try {
String logoUrl = dropboxService.imageUpload(file, ImageType.QUARTER_ACHIEVEMENT_LOGO);
quarterAchievementService.setLogoUrl(logoUrl, quarterId);
return ResponseBuilder.success("LogoUrl", logoUrl);
} catch (IOException | DbxException e) {
return ResponseBuilder.fail(e.getMessage());
}
}
@DeleteMapping("/logo")
@ApiOperation(value = "Delete quarter achievement logo")
public ResponseResult delete(@RequestParam("quarterId") Long quarterId) {
try {
quarterAchievementService.deleteLogo(quarterId);
return ResponseBuilder.success("Logo deleted.");
} catch (DbxException e) {
return ResponseBuilder.fail(e.getMessage());
}
}
}
|
package com.yahoo.sketches.pig.tuple;
import com.yahoo.memory.Memory;
import com.yahoo.sketches.tuple.ArrayOfDoublesSketch;
import com.yahoo.sketches.tuple.ArrayOfDoublesSketches;
import java.io.IOException;
import org.apache.commons.math3.stat.inference.TTest;
import org.apache.commons.math3.stat.StatUtils;
import org.apache.pig.EvalFunc;
import org.apache.pig.data.DataByteArray;
import org.apache.pig.data.Tuple;
/**
* Calculate p-values given two ArrayOfDoublesSketch. Each value in the sketch
* is treated as a separate metric measurement, and a p-value will be generated
* for each metric.
*
* The t-statistic is calculated as follows: t = (m1 - m2) / sqrt(var1/n1 + var2/n2)
*
* Degrees of freedom is approximated by Welch-Satterthwaite.
*/
public class ArrayOfDoublesSketchesToPValueEstimates extends EvalFunc<Tuple> {
@Override
public Tuple exec(final Tuple input) throws IOException {
if ((input == null) || (input.size() != 2)) {
return null;
}
// Get the two sketches
final DataByteArray dbaA = (DataByteArray) input.get(0);
final DataByteArray dbaB = (DataByteArray) input.get(1);
final ArrayOfDoublesSketch sketchA = ArrayOfDoublesSketches.wrapSketch(Memory.wrap(dbaA.get()));
final ArrayOfDoublesSketch sketchB = ArrayOfDoublesSketches.wrapSketch(Memory.wrap(dbaB.get()));
// Check that the size of the arrays in the sketches are the same
if (sketchA.getNumValues() != sketchB.getNumValues()) {
throw new IllegalArgumentException("Both sketches must have the same number of values");
}
// Check if either sketch is empty
if (sketchA.isEmpty() || sketchB.isEmpty()) {
return null;
}
// Check that each sketch has at least 2 values
if (sketchA.getRetainedEntries() < 2 || sketchB.getRetainedEntries() < 2) {
return null;
}
// Get the values from each sketch
double[][] valuesA = sketchA.getValues();
double[][] valuesB = sketchB.getValues();
valuesA = rotateMatrix(valuesA);
valuesB = rotateMatrix(valuesB);
// Calculate the p-values
double[] pValues = new double[valuesA.length];
TTestWithSketch tTest = new TTestWithSketch();
for (int i = 0; i < valuesA.length; i++) {
// Do some special math to get an accurate mean from the sketches
// Take the sum of the values, divide by theta, then divide by the
// estimate number of records.
double meanA = (StatUtils.sum(valuesA[i]) / sketchA.getTheta()) / sketchA.getEstimate();
double meanB = (StatUtils.sum(valuesB[i]) / sketchB.getTheta()) / sketchB.getEstimate();
// Variance is based only on the samples we have in the tuple sketch
double varianceA = StatUtils.variance(valuesA[i]);
double varianceB = StatUtils.variance(valuesB[i]);
// Use the estimated number of uniques
double numA = sketchA.getEstimate();
double numB = sketchB.getEstimate();
pValues[i] = tTest.callTTest(meanA, meanB, varianceA, varianceB, numA, numB);
}
return Util.doubleArrayToTuple(pValues);
}
/**
* Perform a clockwise rotation the output values from the tuple sketch.
*
* @param m Input matrix to rotate
* @return Rotated matrix
*/
private static double[][] rotateMatrix(double[][] m) {
final int width = m.length;
final int height = m[0].length;
double[][] result = new double[height][width];
for (int i = 0; i < width; i++) {
for (int j = 0; j < height; j++) {
result[j][width - 1 - i] = m[i][j];
}
}
return result;
}
/**
* This class exists to get around the protected tTest method.
*/
private class TTestWithSketch extends TTest {
/**
* Call the protected tTest method.
*/
public double callTTest(double m1, double m2, double v1, double v2, double n1, double n2) {
return super.tTest(m1, m2, v1, v2, n1, n2);
}
}
}
|
package org.phenotips.data.internal;
import org.phenotips.Constants;
import org.xwiki.component.annotation.Component;
import org.xwiki.model.EntityType;
import org.xwiki.model.reference.DocumentReference;
import org.xwiki.model.reference.DocumentReferenceResolver;
import org.xwiki.model.reference.EntityReference;
import org.xwiki.model.reference.EntityReferenceSerializer;
import java.util.ArrayList;
import java.util.List;
import javax.inject.Inject;
import javax.inject.Named;
import javax.inject.Singleton;
import org.apache.commons.lang3.StringUtils;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import com.xpn.xwiki.XWiki;
import com.xpn.xwiki.XWikiContext;
import com.xpn.xwiki.XWikiException;
import com.xpn.xwiki.doc.XWikiDocument;
import com.xpn.xwiki.objects.BaseObject;
import com.xpn.xwiki.objects.LargeStringProperty;
import com.xpn.xwiki.objects.StringProperty;
import com.xpn.xwiki.store.XWikiHibernateBaseStore.HibernateCallback;
import com.xpn.xwiki.store.XWikiHibernateStore;
import com.xpn.xwiki.store.migration.DataMigrationException;
import com.xpn.xwiki.store.migration.XWikiDBVersion;
import com.xpn.xwiki.store.migration.hibernate.AbstractHibernateDataMigration;
/**
* Migration for PhenoTips issue #1280: automatically migrate old candidate, rejected and solved genes to the new
* unified genes data structure.
* <ul>
* <li>For each {@code InvestigationClass} object create a new {@code GeneClass} object, copying the {@code gene} and
* {@code comments}) fields, and set the {@code status} as "candidate".</li>
* <li>For each {@code RejectedGenesClass} object create a new {@code GeneClass} object, copying the {@code gene} and
* {@code comments}) fields, and set the {@code status} as "rejected".</li>
* <li>If the {@code PatientClass} has a non-empty {@code solved__gene_id} property, create a new {@code GeneClass}
* object, copying the {@code gene} field, and set the {@code status} as "solved".</li>
* <li>Successfully migrated objects are removed.</li>
* </ul>
*
* @version $Id$
* @since 1.3M1
*/
@Component
@Named("R71490PhenoTips#1280")
@Singleton
public class R71490PhenoTips1280DataMigration extends AbstractHibernateDataMigration implements
HibernateCallback<Object>
{
private static final String GENE_NAME = "gene";
private static final String COMMENTS_NAME = "comments";
private static final String SOLVED_NAME = "solved__gene_id";
private static final String STATUS_NAME = "status";
private static final String OR = "' or o.className = '";
private static final EntityReference PATIENT_CLASS = new EntityReference("PatientClass", EntityType.DOCUMENT,
Constants.CODE_SPACE_REFERENCE);
private static final EntityReference INVESTIGATION_CLASS = new EntityReference("InvestigationClass",
EntityType.DOCUMENT,
Constants.CODE_SPACE_REFERENCE);
private static final EntityReference GENE_CLASS = new EntityReference("GeneClass", EntityType.DOCUMENT,
Constants.CODE_SPACE_REFERENCE);
private static final EntityReference REJECTED_CLASS = new EntityReference("RejectedGenesClass",
EntityType.DOCUMENT,
Constants.CODE_SPACE_REFERENCE);
/** Resolves unprefixed document names to the current wiki. */
@Inject
@Named("current")
private DocumentReferenceResolver<String> resolver;
/** Serializes the class name without the wiki prefix, to be used in the database query. */
@Inject
@Named("compactwiki")
private EntityReferenceSerializer<String> serializer;
/** Resolves class names to the current wiki. */
@Inject
@Named("current")
private DocumentReferenceResolver<EntityReference> entityResolver;
@Override
public String getDescription()
{
return "Migrate all existing gene values to the GeneClass objects";
}
@Override
public XWikiDBVersion getVersion()
{
return new XWikiDBVersion(71490);
}
@Override
public void hibernateMigrate() throws DataMigrationException, XWikiException
{
getStore().executeWrite(getXWikiContext(), this);
}
@Override
public Object doInHibernate(Session session) throws HibernateException, XWikiException
{
XWikiContext context = getXWikiContext();
XWiki xwiki = context.getWiki();
DocumentReference patientClassReference = this.entityResolver.resolve(PATIENT_CLASS);
DocumentReference investigationClassReference = this.entityResolver.resolve(INVESTIGATION_CLASS);
DocumentReference geneClassReference = this.entityResolver.resolve(GENE_CLASS);
DocumentReference rejectedGenesClassReference = this.entityResolver.resolve(REJECTED_CLASS);
Query q =
session.createQuery("select distinct o.name from BaseObject o where o.className = '"
+ this.serializer.serialize(investigationClassReference) + OR
+ this.serializer.serialize(rejectedGenesClassReference) + OR
+ this.serializer.serialize(patientClassReference)
+ "' and exists(from StringProperty p where p.id.id = o.id and p.id.name = '"
+ SOLVED_NAME + "' and p.value <> '')");
@SuppressWarnings("unchecked")
List<String> docs = q.list();
for (String docName : docs) {
XWikiDocument doc = xwiki.getDocument(this.resolver.resolve(docName), context);
List<String> geneList = new ArrayList<>();
migrateSolvedGenes(doc, patientClassReference, geneClassReference, context, geneList);
migrateGenes(doc, rejectedGenesClassReference, geneClassReference, context, geneList, "rejected");
migrateGenes(doc, investigationClassReference, geneClassReference, context, geneList, "candidate");
doc.setComment("Migrate old candidate/rejected/solved genes to GeneClass objects");
doc.setMinorEdit(true);
try {
// There's a bug in XWiki which prevents saving an object in the same session that it was loaded,
// so we must clear the session cache first.
session.clear();
((XWikiHibernateStore) getStore()).saveXWikiDoc(doc, context, false);
session.flush();
} catch (DataMigrationException e) {
}
}
return null;
}
private void migrateSolvedGenes(XWikiDocument doc, DocumentReference patientClassReference,
DocumentReference geneClassReference, XWikiContext context, List<String> geneList)
throws HibernateException, XWikiException
{
BaseObject patient = doc.getXObject(patientClassReference);
StringProperty oldTarget = (StringProperty) patient.get(SOLVED_NAME);
if (oldTarget == null) {
return;
}
patient.removeField(SOLVED_NAME);
String geneName = oldTarget.getValue();
if (!StringUtils.isBlank(geneName)) {
BaseObject gene = doc.newXObject(geneClassReference, context);
gene.setStringValue(GENE_NAME, geneName);
gene.setStringValue(STATUS_NAME, "solved");
geneList.add(geneName);
}
}
private void migrateGenes(XWikiDocument doc, DocumentReference oldGenesClassReference,
DocumentReference geneClassReference, XWikiContext context, List<String> geneList, String status)
throws HibernateException, XWikiException
{
List<BaseObject> genes = doc.getXObjects(oldGenesClassReference);
if (genes == null || genes.isEmpty()) {
return;
}
for (BaseObject gene : genes) {
if (gene == null) {
continue;
}
StringProperty oldGeneNameProp = (StringProperty) gene.get(GENE_NAME);
if (oldGeneNameProp == null || StringUtils.isBlank(oldGeneNameProp.getValue())) {
continue;
}
String geneName = oldGeneNameProp.getValue();
LargeStringProperty oldGeneCommentsProp = (LargeStringProperty) gene.get(COMMENTS_NAME);
String geneComments = null;
if (oldGeneCommentsProp != null && !StringUtils.isBlank(oldGeneCommentsProp.getValue())) {
geneComments = oldGeneCommentsProp.getValue();
}
// check if we already have migrated this gene
if (!geneList.contains(geneName)) {
BaseObject newgene = doc.newXObject(geneClassReference, context);
newgene.setStringValue(GENE_NAME, geneName);
newgene.setStringValue(STATUS_NAME, status);
if (geneComments != null) {
newgene.setLargeStringValue(COMMENTS_NAME, geneComments);
}
geneList.add(geneName);
} else if (geneComments != null) {
String commentUpend = "\nAutomatic migration: gene was duplicated in the " + status + " gene section.";
commentUpend += "\nOriginal comment: \n" + geneComments;
updateComment(geneName, doc, commentUpend, geneClassReference);
}
}
doc.removeXObjects(oldGenesClassReference);
}
private void updateComment(String geneName, XWikiDocument doc, String commentUpend,
DocumentReference geneClassReference) throws HibernateException, XWikiException
{
List<BaseObject> genes = doc.getXObjects(geneClassReference);
for (BaseObject gene : genes) {
if (gene == null) {
continue;
}
StringProperty geneNameProp = (StringProperty) gene.get(GENE_NAME);
if (geneNameProp != null && geneNameProp.getValue().equals(geneName)) {
LargeStringProperty oldGeneCommentsProp = (LargeStringProperty) gene.get(COMMENTS_NAME);
if (oldGeneCommentsProp == null) {
gene.setLargeStringValue(COMMENTS_NAME, commentUpend);
} else {
gene.setLargeStringValue(COMMENTS_NAME, oldGeneCommentsProp.getValue() + commentUpend);
}
}
}
}
}
|
package io.github.lukehutch.fastclasspathscanner.scanner;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import io.github.lukehutch.fastclasspathscanner.scanner.ClasspathElement.ClasspathResource.ClasspathResourceInZipFile;
import io.github.lukehutch.fastclasspathscanner.scanner.ScanSpec.FileMatchProcessorWrapper;
import io.github.lukehutch.fastclasspathscanner.scanner.ScanSpec.FilePathTesterAndMatchProcessorWrapper;
import io.github.lukehutch.fastclasspathscanner.scanner.ScanSpec.ScanSpecPathMatch;
import io.github.lukehutch.fastclasspathscanner.utils.FastManifestParser;
import io.github.lukehutch.fastclasspathscanner.utils.FastPathResolver;
import io.github.lukehutch.fastclasspathscanner.utils.InterruptionChecker;
import io.github.lukehutch.fastclasspathscanner.utils.LogNode;
import io.github.lukehutch.fastclasspathscanner.utils.MultiMapKeyToList;
import io.github.lukehutch.fastclasspathscanner.utils.Recycler;
import io.github.lukehutch.fastclasspathscanner.utils.WorkQueue;
/** A zip/jarfile classpath element. */
class ClasspathElementZip extends ClasspathElement {
/**
* ZipFile recycler -- creates one ZipFile per thread that wants to concurrently access this classpath element.
*/
private Recycler<ZipFile, IOException> zipFileRecycler;
/** Result of parsing the manifest file for this jarfile. */
private FastManifestParser fastManifestParser;
/** A zip/jarfile classpath element. */
ClasspathElementZip(final ClasspathRelativePath classpathElt, final ScanSpec scanSpec, final boolean scanFiles,
final InterruptionChecker interruptionChecker, final WorkQueue<ClasspathRelativePath> workQueue,
final LogNode log) {
super(classpathElt, scanSpec, scanFiles, interruptionChecker, log);
final File classpathEltFile;
try {
classpathEltFile = classpathElt.getFile();
} catch (final IOException e) {
if (log != null) {
log.log("Exception while trying to canonicalize path " + classpathElt.getResolvedPath(), e);
}
ioExceptionOnOpen = true;
return;
}
zipFileRecycler = new Recycler<ZipFile, IOException>() {
@Override
public ZipFile newInstance() throws IOException {
return new ZipFile(classpathEltFile);
}
};
ZipFile zipFile = null;
try {
try {
zipFile = zipFileRecycler.acquire();
} catch (final IOException e) {
if (log != null) {
log.log("Exception opening zipfile " + classpathEltFile, e);
}
ioExceptionOnOpen = true;
return;
}
if (!scanFiles) {
// If not performing a scan, just get the manifest entry manually
fastManifestParser = new FastManifestParser(zipFile, zipFile.getEntry("META-INF/MANIFEST.MF"), log);
} else {
// Scan for path matches within jarfile, and record ZipEntry objects of matching files.
// Will parse the manifest file if it finds it.
final int numEntries = zipFile.size();
fileMatches = new MultiMapKeyToList<>();
classfileMatches = new ArrayList<>(numEntries);
fileToLastModified = new HashMap<>();
scanZipFile(classpathEltFile, zipFile, log);
}
if (fastManifestParser != null && fastManifestParser.classPath != null) {
// Get the classpath elements from the Class-Path manifest entry
// (these are space-delimited).
final String[] manifestClassPathElts = fastManifestParser.classPath.split(" ");
// Class-Path entries in the manifest file are resolved relative to
// the dir the manifest's jarfile is contaiin. Get the parent path.
final String pathOfContainingDir = FastPathResolver.resolve(classpathEltFile.getParent());
// Create child classpath elements from Class-Path entry
childClasspathElts = new ArrayList<>(manifestClassPathElts.length);
for (int i = 0; i < manifestClassPathElts.length; i++) {
final String manifestClassPathElt = manifestClassPathElts[i];
if (!manifestClassPathElt.isEmpty()) {
ClasspathRelativePath childRelativePath = new ClasspathRelativePath(pathOfContainingDir,
manifestClassPathElt);
childClasspathElts.add(childRelativePath);
if (log != null) {
log.log("Found Class-Path entry in manifest: " + manifestClassPathElt + " -> "
+ childRelativePath);
}
}
}
// Schedule child classpath elements for scanning
workQueue.addWorkUnits(childClasspathElts);
}
} finally {
zipFileRecycler.release(zipFile);
}
}
/** Scan a zipfile for file path patterns matching the scan spec. */
private void scanZipFile(final File zipFileFile, final ZipFile zipFile, final LogNode log) {
String prevParentRelativePath = null;
ScanSpecPathMatch prevParentMatchStatus = null;
int entryIdx = 0;
for (final Enumeration<? extends ZipEntry> entries = zipFile.entries(); entries.hasMoreElements();) {
if ((entryIdx++ & 0x3ff) == 0) {
if (interruptionChecker.checkAndReturn()) {
return;
}
}
final ZipEntry zipEntry = entries.nextElement();
String relativePath = zipEntry.getName();
if (relativePath.startsWith("/")) {
// Shouldn't happen with the standard Java zipfile implementation (but just to be safe)
relativePath = relativePath.substring(1);
}
// Ignore directory entries, they are not needed
final boolean isDir = zipEntry.isDirectory();
if (isDir) {
continue;
}
// Get match status of the parent directory if this zipentry file's relative path
// (or reuse the last match status for speed, if the directory name hasn't changed).
final int lastSlashIdx = relativePath.lastIndexOf("/");
final String parentRelativePath = lastSlashIdx < 0 ? "/" : relativePath.substring(0, lastSlashIdx + 1);
final boolean parentRelativePathChanged = !parentRelativePath.equals(prevParentRelativePath);
final ScanSpecPathMatch parentMatchStatus =
prevParentRelativePath == null || parentRelativePathChanged
? scanSpec.pathWhitelistMatchStatus(parentRelativePath) : prevParentMatchStatus;
prevParentRelativePath = parentRelativePath;
prevParentMatchStatus = parentMatchStatus;
// Store entry for manifest file, if present, so that the entry doesn't have to be looked up by name
if (relativePath.equalsIgnoreCase("META-INF/MANIFEST.MF")) {
if (log != null) {
log.log("Found manifest file: " + relativePath);
}
fastManifestParser = new FastManifestParser(zipFile, zipEntry, log);
}
// Class can only be scanned if it's within a whitelisted path subtree, or if it is a classfile
// that has been specifically-whitelisted
if (parentMatchStatus != ScanSpecPathMatch.WITHIN_WHITELISTED_PATH
&& (parentMatchStatus != ScanSpecPathMatch.AT_WHITELISTED_CLASS_PACKAGE
|| !scanSpec.isSpecificallyWhitelistedClass(relativePath))) {
continue;
}
if (log != null) {
log.log("Found whitelisted file in jarfile: " + relativePath);
}
// Store relative paths of any classfiles encountered
if (ClasspathRelativePath.isClassfile(relativePath)) {
classfileMatches.add(new ClasspathResourceInZipFile(zipFileFile, relativePath, zipEntry));
}
// Match file paths against path patterns
for (final FilePathTesterAndMatchProcessorWrapper fileMatcher :
scanSpec.getFilePathTestersAndMatchProcessorWrappers()) {
if (fileMatcher.filePathMatches(zipFileFile, relativePath, log)) {
// File's relative path matches.
// Don't use the last modified time from the individual zipEntry objects,
// we use the last modified time for the zipfile itself instead.
fileMatches.put(fileMatcher.fileMatchProcessorWrapper,
new ClasspathResourceInZipFile(zipFileFile, relativePath, zipEntry));
}
}
}
fileToLastModified.put(zipFileFile, zipFileFile.lastModified());
}
/**
* Open an input stream and call a FileMatchProcessor on a specific whitelisted match found within this zipfile.
*/
@Override
protected void openInputStreamAndProcessFileMatch(final ClasspathResource fileMatchResource,
final FileMatchProcessorWrapper fileMatchProcessorWrapper) throws IOException {
if (!ioExceptionOnOpen) {
// Open InputStream on relative path within zipfile
ZipFile zipFile = null;
try {
zipFile = zipFileRecycler.acquire();
final ZipEntry zipEntry = ((ClasspathResourceInZipFile) fileMatchResource).zipEntry;
try (InputStream inputStream = zipFile.getInputStream(zipEntry)) {
// Run FileMatcher
fileMatchProcessorWrapper.processMatch(fileMatchResource.classpathEltFile,
fileMatchResource.relativePath, inputStream, zipEntry.getSize());
}
} finally {
zipFileRecycler.release(zipFile);
}
}
}
/** Open an input stream and parse a specific classfile found within this zipfile. */
@Override
protected void openInputStreamAndParseClassfile(final ClasspathResource classfileResource,
final ClassfileBinaryParser classfileBinaryParser, final ScanSpec scanSpec,
final ConcurrentHashMap<String, String> stringInternMap,
final ConcurrentLinkedQueue<ClassInfoUnlinked> classInfoUnlinked, final LogNode log)
throws InterruptedException, IOException {
if (!ioExceptionOnOpen) {
ZipFile zipFile = null;
try {
zipFile = zipFileRecycler.acquire();
final ZipEntry zipEntry = ((ClasspathResourceInZipFile) classfileResource).zipEntry;
try (InputStream inputStream = zipFile.getInputStream(zipEntry)) {
// Parse classpath binary format, creating a ClassInfoUnlinked object
final ClassInfoUnlinked thisClassInfoUnlinked = classfileBinaryParser
.readClassInfoFromClassfileHeader(classfileResource.relativePath, inputStream, scanSpec,
stringInternMap, log);
// If class was successfully read, output new ClassInfoUnlinked object
if (thisClassInfoUnlinked != null) {
classInfoUnlinked.add(thisClassInfoUnlinked);
thisClassInfoUnlinked.logTo(log);
}
}
} finally {
zipFileRecycler.release(zipFile);
}
}
}
/** Close all open ZipFiles. */
@Override
public void close() {
if (zipFileRecycler != null) {
zipFileRecycler.close();
}
}
}
|
package org.jboss.as.controller.remote;
import static java.security.AccessController.doPrivileged;
import static org.jboss.as.controller.logging.ControllerLogger.MGMT_OP_LOGGER;
import java.security.PrivilegedAction;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.RejectedExecutionException;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import org.jboss.as.controller.ModelController;
import org.jboss.as.protocol.mgmt.support.ManagementChannelInitialization;
import org.jboss.msc.service.Service;
import org.jboss.msc.service.ServiceName;
import org.jboss.msc.service.StartContext;
import org.jboss.msc.service.StartException;
import org.jboss.msc.service.StopContext;
import org.jboss.msc.value.InjectedValue;
import org.jboss.threads.EnhancedQueueExecutor;
import org.jboss.threads.JBossThreadFactory;
/**
* Service used to create operation handlers per incoming channel
*
* @author <a href="kabir.khan@jboss.com">Kabir Khan</a>
*/
public abstract class AbstractModelControllerOperationHandlerFactoryService implements Service<AbstractModelControllerOperationHandlerFactoryService>, ManagementChannelInitialization {
public static final ServiceName OPERATION_HANDLER_NAME_SUFFIX = ServiceName.of("operation", "handler");
// The defaults if no executor was defined
private static final int WORK_QUEUE_SIZE = 512;
private static final int POOL_CORE_SIZE = 4;
private static final int POOL_MAX_SIZE = 4;
private final InjectedValue<ModelController> modelControllerValue = new InjectedValue<ModelController>();
private final InjectedValue<ExecutorService> executor = new InjectedValue<ExecutorService>();
private final InjectedValue<ScheduledExecutorService> scheduledExecutor = new InjectedValue<>();
private ResponseAttachmentInputStreamSupport responseAttachmentSupport;
private ExecutorService clientRequestExecutor;
/**
* Use to inject the model controller that will be the target of the operations
*
* @return the injected value holder
*/
public InjectedValue<ModelController> getModelControllerInjector() {
return modelControllerValue;
}
public InjectedValue<ExecutorService> getExecutorInjector() {
return executor;
}
public InjectedValue<ScheduledExecutorService> getScheduledExecutorInjector() {
return scheduledExecutor;
}
/** {@inheritDoc} */
@Override
public synchronized void start(StartContext context) throws StartException {
MGMT_OP_LOGGER.debugf("Starting operation handler service %s", context.getController().getName());
responseAttachmentSupport = new ResponseAttachmentInputStreamSupport(scheduledExecutor.getValue());
final ThreadFactory threadFactory = doPrivileged(new PrivilegedAction<JBossThreadFactory>() {
public JBossThreadFactory run() {
return new JBossThreadFactory(new ThreadGroup("management-handler-thread"), Boolean.FALSE, null, "%G - %t", null, null);
}
});
if (EnhancedQueueExecutor.DISABLE_HINT) {
ThreadPoolExecutor executor = new ThreadPoolExecutor(POOL_CORE_SIZE, POOL_MAX_SIZE,
600L, TimeUnit.SECONDS, new LinkedBlockingDeque<>(WORK_QUEUE_SIZE),
threadFactory);
// Allow the core threads to time out as well
executor.allowCoreThreadTimeOut(true);
this.clientRequestExecutor = executor;
} else {
this.clientRequestExecutor = new EnhancedQueueExecutor.Builder()
.setCorePoolSize(POOL_CORE_SIZE)
.setMaximumPoolSize(POOL_MAX_SIZE)
.setKeepAliveTime(600L, TimeUnit.SECONDS)
.setMaximumQueueSize(WORK_QUEUE_SIZE)
.setThreadFactory(threadFactory)
.allowCoreThreadTimeOut(true)
.build();
}
}
/** {@inheritDoc} */
@Override
public synchronized void stop(final StopContext stopContext) {
final ExecutorService executorService = executor.getValue();
final Runnable task = new Runnable() {
@Override
public void run() {
try {
responseAttachmentSupport.shutdown();
// Shut down new requests to the client request executor,
// but don't mess with currently running tasks
clientRequestExecutor.shutdown();
} finally {
stopContext.complete();
}
}
};
try {
executorService.execute(task);
} catch (RejectedExecutionException e) {
task.run();
} finally {
stopContext.asynchronous();
}
}
/** {@inheritDoc} */
@Override
public synchronized AbstractModelControllerOperationHandlerFactoryService getValue() throws IllegalStateException {
return this;
}
protected ModelController getController() {
return modelControllerValue.getValue();
}
protected ExecutorService getExecutor() {
return executor.getValue();
}
protected ResponseAttachmentInputStreamSupport getResponseAttachmentSupport() {
return responseAttachmentSupport;
}
protected final ExecutorService getClientRequestExecutor() {
return clientRequestExecutor;
}
}
|
package io.github.thatsmusic99.headsplus.commands.maincommand;
import io.github.thatsmusic99.headsplus.HeadsPlus;
import io.github.thatsmusic99.headsplus.api.HPPlayer;
import io.github.thatsmusic99.headsplus.commands.CommandInfo;
import io.github.thatsmusic99.headsplus.commands.IHeadsPlusCommand;
import io.github.thatsmusic99.headsplus.config.ConfigTextMenus;
import io.github.thatsmusic99.headsplus.config.HeadsPlusMessagesManager;
import io.github.thatsmusic99.headsplus.util.HPUtils;
import org.bukkit.Bukkit;
import org.bukkit.OfflinePlayer;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.util.StringUtil;
import org.jetbrains.annotations.NotNull;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
@CommandInfo(
commandname = "profile",
permission = "headsplus.maincommand.profile",
maincommand = true,
usage = "/hp profile [Player]",
descriptionPath = "descriptions.hp.profile"
)
public class ProfileCommand implements IHeadsPlusCommand {
private String prof(OfflinePlayer p, CommandSender sender) throws SQLException {
try {
HPPlayer pl = HPPlayer.getHPPlayer(p);
return ConfigTextMenus.ProfileTranslator.translate(pl, sender);
} catch (NullPointerException ex) {
ex.printStackTrace();
return HeadsPlusMessagesManager.get().getString("commands.errors.no-data", sender);
}
}
@Override
public boolean fire(String[] args, CommandSender cs) {
String name = cs.getName();
if (args.length != 1) {
name = args[1];
}
HPUtils.getOfflinePlayer(name).thenAccept(player -> {
try {
if (cs instanceof Player) {
if (cs.getName().equalsIgnoreCase(player.getName())) {
cs.sendMessage(prof(player, cs));
} else {
if (cs.hasPermission("headsplus.maincommand.profile.others")) {
cs.sendMessage(prof(player, cs));
} else {
HeadsPlusMessagesManager.get().sendMessage("commands.errors.no-perm", cs);
}
}
} else {
if (cs.getName().equalsIgnoreCase(player.getName())) {
// Not a player
cs.sendMessage(HeadsPlusMessagesManager.get().getString("commands.profile.cant-view-data"));
} else {
cs.sendMessage(prof(player, cs));
}
}
} catch (SQLException e) {
DebugPrint.createReport(e, "Subcommand (profile)", true, cs);
}
});
return true;
}
@Override
public boolean shouldEnable() {
return true;
}
@Override
public List<String> onTabComplete(@NotNull CommandSender sender, @NotNull Command cmd, @NotNull String label, @NotNull String[] args) {
List<String> results = new ArrayList<>();
if (args.length == 2) {
StringUtil.copyPartialMatches(args[1], IHeadsPlusCommand.getPlayers(sender), results);
}
return results;
}
}
|
package net.sf.taverna.t2.workbench.reference.config;
import java.util.HashMap;
import java.util.Map;
import net.sf.taverna.t2.workbench.configuration.AbstractConfigurable;
/**
* Configuration for the reference service and provenance.
*
* @author David Withers
* @author Stuart Owen
*/
public class DataManagementConfiguration extends AbstractConfigurable {
public static final String IN_MEMORY = "in_memory";
public static final String ENABLE_PROVENANCE = "provenance";
public static final String CONNECTOR_TYPE = "connector";
public static final String PORT = "port";
public static final String CURRENT_PORT = "current_port";
public static final String REFERENCE_SERVICE_CONTEXT = "referenceService.context";
public static final String IN_MEMORY_CONTEXT = "inMemoryReferenceServiceContext.xml";
public static final String HIBERNATE_CONTEXT = "hibernateReferenceServiceContext.xml";
public static final String HIBERNATE_DIALECT = "dialect";
public static final String START_INTERNAL_DERBY = "start_derby";
public static final String POOL_MAX_ACTIVE = "pool_max_active";
public static final String POOL_MIN_IDLE = "pool_min_idle";
public static final String POOL_MAX_IDLE = "pool_max_idle";
public static final String DRIVER_CLASS_NAME = "driver";
public static final String JDBC_URI = "jdbcuri";
public static final String USERNAME = "username";
public static final String PASSWORD = "password";
//FIXME: these should me just mysql & derby - but build & dependency issues is causing the provenance to expect these values:
public static final String CONNECTOR_MYSQL="mysql";
public static final String CONNECTOR_DERBY="derby";
public static final String JNDI_NAME = "jdbc/taverna";
private Map<String, String> defaultPropertyMap;
private static DataManagementConfiguration instance;
public static DataManagementConfiguration getInstance() {
if (instance == null) {
instance = new DataManagementConfiguration();
if (instance.getStartInternalDerbyServer()) {
DataManagementHelper.startDerbyNetworkServer();
}
DataManagementHelper.setupDataSource();
}
return instance;
}
public String getDatabaseContext() {
if (getProperty(IN_MEMORY).equalsIgnoreCase("true")) {
return IN_MEMORY_CONTEXT;
} else {
return HIBERNATE_CONTEXT;
}
}
public String getDriverClassName() {
return getProperty(DRIVER_CLASS_NAME);
}
public boolean isProvenanceEnabled() {
return getProperty(ENABLE_PROVENANCE).equalsIgnoreCase("true");
}
public boolean getStartInternalDerbyServer() {
return getProperty(START_INTERNAL_DERBY).equalsIgnoreCase("true");
}
public int getPort() {
return Integer.valueOf(getProperty(PORT));
}
public void setCurrentPort(int port) {
setProperty(CURRENT_PORT, String.valueOf(port));
}
public int getCurrentPort() {
return Integer.valueOf(getProperty(CURRENT_PORT));
}
public int getPoolMaxActive() {
return Integer.valueOf(getProperty(POOL_MAX_ACTIVE));
}
public int getPoolMinIdle() {
return Integer.valueOf(getProperty(POOL_MIN_IDLE));
}
public int getPoolMaxIdle() {
return Integer.valueOf(getProperty(POOL_MAX_IDLE));
}
private DataManagementConfiguration() {
}
public String getCategory() {
return "general";
}
public Map<String, String> getDefaultPropertyMap() {
if (defaultPropertyMap == null) {
defaultPropertyMap = new HashMap<String, String>();
defaultPropertyMap.put(IN_MEMORY, "true");
defaultPropertyMap.put(ENABLE_PROVENANCE, "true");
defaultPropertyMap.put(PORT, "1527");
//defaultPropertyMap.put(DRIVER_CLASS_NAME, "org.apache.derby.jdbc.ClientDriver");
defaultPropertyMap.put(DRIVER_CLASS_NAME, "org.apache.derby.jdbc.EmbeddedDriver");
defaultPropertyMap.put(HIBERNATE_DIALECT, "org.hibernate.dialect.DerbyDialect");
defaultPropertyMap.put(POOL_MAX_ACTIVE, "50");
defaultPropertyMap.put(POOL_MAX_IDLE, "50");
defaultPropertyMap.put(POOL_MIN_IDLE, "10");
defaultPropertyMap.put(USERNAME,"");
defaultPropertyMap.put(PASSWORD,"");
defaultPropertyMap.put(JDBC_URI,"jdbc:derby:t2-database;create=true;upgrade=true");
defaultPropertyMap.put(START_INTERNAL_DERBY, "false");
defaultPropertyMap.put(CONNECTOR_TYPE,CONNECTOR_DERBY);
}
return defaultPropertyMap;
}
public String getHibernateDialect() {
return getProperty(HIBERNATE_DIALECT);
}
public String getDisplayName() {
return "Data and provenance";
}
public String getFilePrefix() {
return "DataAndProvenance";
}
public String getUUID() {
return "6BD3F5C1-C68D-4893-8D9B-2F46FA1DDB19";
}
public String getConnectorType() {
return getProperty(CONNECTOR_TYPE);
}
public String getJDBCUri() {
if (CONNECTOR_DERBY.equals(getConnectorType()) && getStartInternalDerbyServer()) {
return "jdbc:derby://localhost:" + getCurrentPort() + "/t2-database;create=true;upgrade=true";
}
else {
return getProperty(JDBC_URI);
}
}
public String getUsername() {
return getProperty(USERNAME);
}
public String getPassword() {
return getProperty(PASSWORD);
}
}
|
package net.finmath.montecarlo.assetderivativevaluation;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;
import net.finmath.exception.CalculationException;
import net.finmath.montecarlo.IndependentIncrements;
import net.finmath.montecarlo.model.ProcessModel;
import net.finmath.montecarlo.process.EulerSchemeFromProcessModel;
import net.finmath.montecarlo.process.MonteCarloProcess;
import net.finmath.stochastic.RandomVariable;
import net.finmath.time.TimeDiscretization;
/**
* This class glues together an <code>AbstractProcessModel</code> and a Monte-Carlo implementation of a <code>MonteCarloProcessFromProcessModel</code>
* and implements <code>AssetModelMonteCarloSimulationModel</code>.
*
* The model is specified via the object implementing <code>ProcessModel</code>.
*
* @author Christian Fries
* @see net.finmath.montecarlo.process.MonteCarloProcess The interface for numerical schemes.
* @see net.finmath.montecarlo.model.ProcessModel The interface for models provinding parameters to numerical schemes.
* @version 1.0
*/
public class MonteCarloAssetModel implements AssetModelMonteCarloSimulationModel {
private final ProcessModel model;
private final MonteCarloProcess process;
/**
* Create a Monte-Carlo simulation using given process discretization scheme.
*
* @param process The numerical scheme to be used.
*/
public MonteCarloAssetModel(final MonteCarloProcess process) {
super();
this.model = process.getModel();
this.process = process;
}
/**
* Create a Monte-Carlo simulation using given process discretization scheme.
*
* @param model The model to be used.
* @param process The numerical scheme to be used.
*/
public MonteCarloAssetModel(
final ProcessModel model,
final MonteCarloProcess process) {
super();
this.model = model;
this.process = process;
}
public MonteCarloAssetModel(ProcessModel model, IndependentIncrements stochasticDriver) {
super();
this.model = model;
this.process = new EulerSchemeFromProcessModel(model, stochasticDriver);
}
@Override
public RandomVariable getAssetValue(final double time, final int assetIndex) throws CalculationException {
int timeIndex = getTimeIndex(time);
if(timeIndex < 0) {
throw new IllegalArgumentException("The model does not provide an interpolation of simulation time (time given was " + time + ").");
}
return getAssetValue(timeIndex, assetIndex);
}
@Override
public RandomVariable getAssetValue(final int timeIndex, final int assetIndex) throws CalculationException {
return process.getProcessValue(timeIndex, assetIndex);
}
@Override
public RandomVariable getNumeraire(final int timeIndex) throws CalculationException {
final double time = getTime(timeIndex);
// TODO Add caching of the numerare here!
return model.getNumeraire(process, time);
}
@Override
public RandomVariable getNumeraire(final double time) throws CalculationException {
// TODO Add caching of the numerare here!
return model.getNumeraire(process, time);
}
@Override
public RandomVariable getMonteCarloWeights(final double time) throws CalculationException {
return getMonteCarloWeights(getTimeIndex(time));
}
@Override
public int getNumberOfAssets() {
return 1;
}
@Override
public AssetModelMonteCarloSimulationModel getCloneWithModifiedData(final Map<String, Object> dataModified) throws CalculationException {
final ProcessModel newModel = model.getCloneWithModifiedData(dataModified);
MonteCarloProcess newProcess;
try {
final Map<String, Object> dataModifiedForProcess = new HashMap<String, Object>();
dataModifiedForProcess.putAll(dataModified);
if(!dataModifiedForProcess.containsKey("model")) {
dataModifiedForProcess.put("model", newModel);
}
newProcess = process.getCloneWithModifiedData(dataModifiedForProcess);
}
catch(final UnsupportedOperationException e) {
newProcess = process;
}
// In the case where the model has changed we need a new process anyway
if(newModel != model && newProcess == process) {
newProcess = process.getCloneWithModifiedModel(newModel);
}
return new MonteCarloAssetModel(newModel, newProcess);
}
/**
* The method is not implemented. Instead call getCloneWithModifiedData on the model
* an create a new process from it.
*
* @param seed The new seed.
*/
@Override
@Deprecated
public AssetModelMonteCarloSimulationModel getCloneWithModifiedSeed(final int seed) {
throw new UnsupportedOperationException("Method not implemented");
}
@Override
public int getNumberOfPaths() {
return process.getNumberOfPaths();
}
@Override
public LocalDateTime getReferenceDate() {
return model.getReferenceDate();
}
@Override
public TimeDiscretization getTimeDiscretization() {
return process.getTimeDiscretization();
}
@Override
public double getTime(final int timeIndex) {
return process.getTime(timeIndex);
}
@Override
public int getTimeIndex(final double time) {
return process.getTimeIndex(time);
}
@Override
public RandomVariable getRandomVariableForConstant(final double value) {
return model.getRandomVariableForConstant(value);
}
@Override
public RandomVariable getMonteCarloWeights(final int timeIndex) throws CalculationException {
return process.getMonteCarloWeights(timeIndex);
}
/**
* Returns the {@link ProcessModel} used for this Monte-Carlo simulation.
*
* @return the model
*/
public ProcessModel getModel() {
return model;
}
/**
* Returns the {@link MonteCarloProcess} used for this Monte-Carlo simulation.
*
* @return the process
*/
public MonteCarloProcess getProcess() {
return process;
}
@Override
public String toString() {
return this.getClass().getSimpleName() + " [model=" + model + "]";
}
}
|
package org.hisp.dhis.dxf2.metadata;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hisp.dhis.common.IdentifiableObject;
import org.hisp.dhis.common.SetMap;
import org.hisp.dhis.commons.timer.SystemTimer;
import org.hisp.dhis.commons.timer.Timer;
import org.hisp.dhis.dataelement.DataElement;
import org.hisp.dhis.dataelement.DataElementCategory;
import org.hisp.dhis.dataelement.DataElementCategoryCombo;
import org.hisp.dhis.dataelement.DataElementCategoryOption;
import org.hisp.dhis.dataelement.DataElementCategoryOptionCombo;
import org.hisp.dhis.dataelement.DataElementOperand;
import org.hisp.dhis.dataentryform.DataEntryForm;
import org.hisp.dhis.dataset.DataSet;
import org.hisp.dhis.dataset.DataSetElement;
import org.hisp.dhis.dataset.Section;
import org.hisp.dhis.dxf2.common.OrderParams;
import org.hisp.dhis.fieldfilter.FieldFilterService;
import org.hisp.dhis.indicator.Indicator;
import org.hisp.dhis.indicator.IndicatorType;
import org.hisp.dhis.legend.Legend;
import org.hisp.dhis.legend.LegendSet;
import org.hisp.dhis.node.NodeUtils;
import org.hisp.dhis.node.types.ComplexNode;
import org.hisp.dhis.node.types.RootNode;
import org.hisp.dhis.node.types.SimpleNode;
import org.hisp.dhis.option.Option;
import org.hisp.dhis.option.OptionSet;
import org.hisp.dhis.program.Program;
import org.hisp.dhis.program.ProgramIndicator;
import org.hisp.dhis.program.ProgramStage;
import org.hisp.dhis.program.ProgramStageDataElement;
import org.hisp.dhis.program.ProgramStageSection;
import org.hisp.dhis.program.ProgramTrackedEntityAttribute;
import org.hisp.dhis.programrule.ProgramRule;
import org.hisp.dhis.programrule.ProgramRuleAction;
import org.hisp.dhis.programrule.ProgramRuleService;
import org.hisp.dhis.programrule.ProgramRuleVariable;
import org.hisp.dhis.programrule.ProgramRuleVariableService;
import org.hisp.dhis.query.Query;
import org.hisp.dhis.query.QueryService;
import org.hisp.dhis.schema.Schema;
import org.hisp.dhis.schema.SchemaService;
import org.hisp.dhis.system.SystemInfo;
import org.hisp.dhis.system.SystemService;
import org.hisp.dhis.trackedentity.TrackedEntity;
import org.hisp.dhis.trackedentity.TrackedEntityAttribute;
import org.hisp.dhis.user.CurrentUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* @author Morten Olav Hansen <mortenoh@gmail.com>
*/
@Component
public class DefaultMetadataExportService implements MetadataExportService
{
private static final Log log = LogFactory.getLog( MetadataExportService.class );
@Autowired
private SchemaService schemaService;
@Autowired
private QueryService queryService;
@Autowired
private FieldFilterService fieldFilterService;
@Autowired
private CurrentUserService currentUserService;
@Autowired
private ProgramRuleService programRuleService;
@Autowired
private ProgramRuleVariableService programRuleVariableService;
@Autowired
private SystemService systemService;
@Override
@SuppressWarnings( "unchecked" )
public Map<Class<? extends IdentifiableObject>, List<? extends IdentifiableObject>> getMetadata( MetadataExportParams params )
{
Timer timer = new SystemTimer().start();
Map<Class<? extends IdentifiableObject>, List<? extends IdentifiableObject>> metadata = new HashMap<>();
if ( params.getUser() == null )
{
params.setUser( currentUserService.getCurrentUser() );
}
if ( params.getClasses().isEmpty() )
{
schemaService.getMetadataSchemas().stream().filter( Schema::isIdentifiableObject )
.forEach( schema -> params.getClasses().add( (Class<? extends IdentifiableObject>) schema.getKlass() ) );
}
log.info( "(" + params.getUsername() + ") Export:Start" );
for ( Class<? extends IdentifiableObject> klass : params.getClasses() )
{
Query query;
if ( params.getQuery( klass ) != null )
{
query = params.getQuery( klass );
}
else
{
OrderParams orderParams = new OrderParams( Sets.newHashSet( params.getDefaultOrder() ) );
query = queryService.getQueryFromUrl( klass, params.getDefaultFilter(), orderParams.getOrders( schemaService.getDynamicSchema( klass ) ) );
}
if ( query.getUser() == null )
{
query.setUser( params.getUser() );
}
query.setDefaultOrder();
List<? extends IdentifiableObject> objects = queryService.query( query );
if ( !objects.isEmpty() )
{
log.info( "(" + params.getUsername() + ") Exported " + objects.size() + " objects of type " + klass.getSimpleName() );
metadata.put( klass, objects );
}
}
log.info( "(" + params.getUsername() + ") Export:Done took " + timer.toString() );
return metadata;
}
@Override
public RootNode getMetadataAsNode( MetadataExportParams params )
{
RootNode rootNode = NodeUtils.createMetadata();
SystemInfo systemInfo = systemService.getSystemInfo();
ComplexNode system = rootNode.addChild( new ComplexNode( "system" ) );
system.addChild( new SimpleNode( "id", systemInfo.getSystemId() ) );
system.addChild( new SimpleNode( "rev", systemInfo.getRevision() ) );
system.addChild( new SimpleNode( "version", systemInfo.getVersion() ) );
system.addChild( new SimpleNode( "date", systemInfo.getServerDate() ) );
Map<Class<? extends IdentifiableObject>, List<? extends IdentifiableObject>> metadata = getMetadata( params );
for ( Class<? extends IdentifiableObject> klass : metadata.keySet() )
{
rootNode.addChild( fieldFilterService.filter( klass, metadata.get( klass ), params.getFields( klass ) ) );
}
return rootNode;
}
@Override
public void validate( MetadataExportParams params )
{
}
@Override
@SuppressWarnings( "unchecked" )
public MetadataExportParams getParamsFromMap( Map<String, List<String>> parameters )
{
MetadataExportParams params = new MetadataExportParams();
Map<Class<? extends IdentifiableObject>, Map<String, List<String>>> map = new HashMap<>();
if ( parameters.containsKey( "fields" ) )
{
params.setDefaultFields( parameters.get( "fields" ) );
parameters.remove( "fields" );
}
if ( parameters.containsKey( "filter" ) )
{
params.setDefaultFilter( parameters.get( "filter" ) );
parameters.remove( "filter" );
}
if ( parameters.containsKey( "order" ) )
{
params.setDefaultOrder( parameters.get( "order" ) );
parameters.remove( "order" );
}
for ( String parameterKey : parameters.keySet() )
{
String[] parameter = parameterKey.split( ":" );
Schema schema = schemaService.getSchemaByPluralName( parameter[0] );
if ( schema == null || !schema.isIdentifiableObject() )
{
continue;
}
Class<? extends IdentifiableObject> klass = (Class<? extends IdentifiableObject>) schema.getKlass();
// class is enabled if value = true, or fields/filter/order is present
if ( "true".equalsIgnoreCase( parameters.get( parameterKey ).get( 0 ) ) || (parameter.length > 1 && ("fields".equalsIgnoreCase( parameter[1] )
|| "filter".equalsIgnoreCase( parameter[1] ) || "order".equalsIgnoreCase( parameter[1] ))) )
{
if ( !map.containsKey( klass ) ) map.put( klass, new HashMap<>() );
}
else
{
continue;
}
if ( parameter.length > 1 )
{
if ( "fields".equalsIgnoreCase( parameter[1] ) )
{
if ( !map.get( klass ).containsKey( "fields" ) ) map.get( klass ).put( "fields", new ArrayList<>() );
map.get( klass ).get( "fields" ).addAll( parameters.get( parameterKey ) );
}
if ( "filter".equalsIgnoreCase( parameter[1] ) )
{
if ( !map.get( klass ).containsKey( "filter" ) ) map.get( klass ).put( "filter", new ArrayList<>() );
map.get( klass ).get( "filter" ).addAll( parameters.get( parameterKey ) );
}
if ( "order".equalsIgnoreCase( parameter[1] ) )
{
if ( !map.get( klass ).containsKey( "order" ) ) map.get( klass ).put( "order", new ArrayList<>() );
map.get( klass ).get( "order" ).addAll( parameters.get( parameterKey ) );
}
}
}
map.keySet().forEach( params::addClass );
for ( Class<? extends IdentifiableObject> klass : map.keySet() )
{
Map<String, List<String>> classMap = map.get( klass );
Schema schema = schemaService.getDynamicSchema( klass );
if ( classMap.containsKey( "fields" ) ) params.addFields( klass, classMap.get( "fields" ) );
if ( classMap.containsKey( "filter" ) && classMap.containsKey( "order" ) )
{
OrderParams orderParams = new OrderParams( Sets.newHashSet( classMap.get( "order" ) ) );
Query query = queryService.getQueryFromUrl( klass, classMap.get( "filter" ), orderParams.getOrders( schema ) );
query.setDefaultOrder();
params.addQuery( query );
}
else if ( classMap.containsKey( "filter" ) )
{
Query query = queryService.getQueryFromUrl( klass, classMap.get( "filter" ), new ArrayList<>() );
query.setDefaultOrder();
params.addQuery( query );
}
else if ( classMap.containsKey( "order" ) )
{
OrderParams orderParams = new OrderParams();
orderParams.setOrder( Sets.newHashSet( classMap.get( "order" ) ) );
Query query = queryService.getQueryFromUrl( klass, new ArrayList<>(), orderParams.getOrders( schema ) );
query.setDefaultOrder();
params.addQuery( query );
}
}
return params;
}
@Override
public SetMap<Class<? extends IdentifiableObject>, IdentifiableObject> getMetadataWithDependencies( IdentifiableObject object )
{
SetMap<Class<? extends IdentifiableObject>, IdentifiableObject> metadata = new SetMap<>();
if ( DataSet.class.isInstance( object ) ) return handleDataSet( metadata, (DataSet) object );
if ( Program.class.isInstance( object ) ) return handleProgram( metadata, (Program) object );
return metadata;
}
@Override
public RootNode getMetadataWithDependenciesAsNode( IdentifiableObject object )
{
RootNode rootNode = NodeUtils.createMetadata();
rootNode.addChild( new SimpleNode( "date", new Date(), true ) );
SetMap<Class<? extends IdentifiableObject>, IdentifiableObject> metadata = getMetadataWithDependencies( object );
for ( Class<? extends IdentifiableObject> klass : metadata.keySet() )
{
rootNode.addChild( fieldFilterService.filter( klass, Lists.newArrayList( metadata.get( klass ) ), Lists.newArrayList( ":owner" ) ) );
}
return rootNode;
}
// Utility Methods
private SetMap<Class<? extends IdentifiableObject>, IdentifiableObject> handleDataSet( SetMap<Class<? extends IdentifiableObject>, IdentifiableObject> metadata, DataSet dataSet )
{
metadata.putValue( DataSet.class, dataSet );
dataSet.getDataSetElements().forEach( dataSetElement -> handleDataSetElement( metadata, dataSetElement ) );
dataSet.getSections().forEach( section -> handleSection( metadata, section ) );
dataSet.getIndicators().forEach( indicator -> handleIndicator( metadata, indicator ) );
handleDataEntryForm( metadata, dataSet.getDataEntryForm() );
handleLegendSet( metadata, dataSet.getLegendSet() );
handleCategoryCombo( metadata, dataSet.getCategoryCombo() );
dataSet.getCompulsoryDataElementOperands().forEach( dataElementOperand -> handleDataElementOperand( metadata, dataElementOperand ) );
return metadata;
}
private SetMap<Class<? extends IdentifiableObject>, IdentifiableObject> handleDataElementOperand( SetMap<Class<? extends IdentifiableObject>, IdentifiableObject> metadata, DataElementOperand dataElementOperand )
{
if ( dataElementOperand == null ) return metadata;
handleCategoryOptionCombo( metadata, dataElementOperand.getCategoryOptionCombo() );
handleLegendSet( metadata, dataElementOperand.getLegendSet() );
handleDataElement( metadata, dataElementOperand.getDataElement() );
return metadata;
}
private SetMap<Class<? extends IdentifiableObject>, IdentifiableObject> handleCategoryOptionCombo( SetMap<Class<? extends IdentifiableObject>, IdentifiableObject> metadata, DataElementCategoryOptionCombo categoryOptionCombo )
{
if ( categoryOptionCombo == null ) return metadata;
metadata.putValue( DataElementCategoryOptionCombo.class, categoryOptionCombo );
handleCategoryCombo( metadata, categoryOptionCombo.getCategoryCombo() );
categoryOptionCombo.getCategoryOptions().forEach( categoryOption -> handleCategoryOption( metadata, categoryOption ) );
return metadata;
}
private SetMap<Class<? extends IdentifiableObject>, IdentifiableObject> handleCategoryCombo( SetMap<Class<? extends IdentifiableObject>, IdentifiableObject> metadata, DataElementCategoryCombo categoryCombo )
{
if ( categoryCombo == null ) return metadata;
metadata.putValue( DataElementCategoryCombo.class, categoryCombo );
categoryCombo.getCategories().forEach( category -> handleCategory( metadata, category ) );
return metadata;
}
private SetMap<Class<? extends IdentifiableObject>, IdentifiableObject> handleCategory( SetMap<Class<? extends IdentifiableObject>, IdentifiableObject> metadata, DataElementCategory category )
{
if ( category == null ) return metadata;
metadata.putValue( DataElementCategory.class, category );
category.getCategoryOptions().forEach( categoryOption -> handleCategoryOption( metadata, categoryOption ) );
return metadata;
}
private SetMap<Class<? extends IdentifiableObject>, IdentifiableObject> handleCategoryOption( SetMap<Class<? extends IdentifiableObject>, IdentifiableObject> metadata, DataElementCategoryOption categoryOption )
{
if ( categoryOption == null ) return metadata;
metadata.putValue( DataElementCategoryOption.class, categoryOption );
categoryOption.getCategoryOptionCombos().forEach( categoryOptionCombo -> handleCategoryOptionCombo( metadata, categoryOptionCombo ) );
return metadata;
}
private SetMap<Class<? extends IdentifiableObject>, IdentifiableObject> handleLegendSet( SetMap<Class<? extends IdentifiableObject>, IdentifiableObject> metadata, LegendSet legendSet )
{
if ( legendSet == null ) return metadata;
metadata.putValue( LegendSet.class, legendSet );
legendSet.getLegends().forEach( legend -> handleLegend( metadata, legend ) );
return metadata;
}
private SetMap<Class<? extends IdentifiableObject>, IdentifiableObject> handleLegend( SetMap<Class<? extends IdentifiableObject>, IdentifiableObject> metadata, Legend legend )
{
if ( legend == null ) return metadata;
metadata.putValue( Legend.class, legend );
return metadata;
}
private SetMap<Class<? extends IdentifiableObject>, IdentifiableObject> handleDataEntryForm( SetMap<Class<? extends IdentifiableObject>, IdentifiableObject> metadata, DataEntryForm dataEntryForm )
{
if ( dataEntryForm == null ) return metadata;
metadata.putValue( DataEntryForm.class, dataEntryForm );
return metadata;
}
private SetMap<Class<? extends IdentifiableObject>, IdentifiableObject> handleDataSetElement( SetMap<Class<? extends IdentifiableObject>, IdentifiableObject> metadata, DataSetElement dataSetElement )
{
if ( dataSetElement == null ) return metadata;
metadata.putValue( DataSetElement.class, dataSetElement );
handleDataElement( metadata, dataSetElement.getDataElement() );
handleCategoryCombo( metadata, dataSetElement.getCategoryCombo() );
return metadata;
}
private SetMap<Class<? extends IdentifiableObject>, IdentifiableObject> handleDataElement( SetMap<Class<? extends IdentifiableObject>, IdentifiableObject> metadata, DataElement dataElement )
{
if ( dataElement == null ) return metadata;
metadata.putValue( DataElement.class, dataElement );
handleCategoryCombo( metadata, dataElement.getDataElementCategoryCombo() );
handleOptionSet( metadata, dataElement.getOptionSet() );
handleOptionSet( metadata, dataElement.getCommentOptionSet() );
return metadata;
}
private SetMap<Class<? extends IdentifiableObject>, IdentifiableObject> handleOptionSet( SetMap<Class<? extends IdentifiableObject>, IdentifiableObject> metadata, OptionSet optionSet )
{
if ( optionSet == null ) return metadata;
metadata.putValue( OptionSet.class, optionSet );
optionSet.getOptions().forEach( o -> handleOption( metadata, o ) );
return metadata;
}
private SetMap<Class<? extends IdentifiableObject>, IdentifiableObject> handleOption( SetMap<Class<? extends IdentifiableObject>, IdentifiableObject> metadata, Option option )
{
if ( option == null ) return metadata;
metadata.putValue( Option.class, option );
return metadata;
}
private SetMap<Class<? extends IdentifiableObject>, IdentifiableObject> handleSection( SetMap<Class<? extends IdentifiableObject>, IdentifiableObject> metadata, Section section )
{
if ( section == null ) return metadata;
metadata.putValue( Section.class, section );
section.getGreyedFields().forEach( dataElementOperand -> handleDataElementOperand( metadata, dataElementOperand ) );
section.getIndicators().forEach( indicator -> handleIndicator( metadata, indicator ) );
section.getDataElements().forEach( dataElement -> handleDataElement( metadata, dataElement ) );
return metadata;
}
private SetMap<Class<? extends IdentifiableObject>, IdentifiableObject> handleIndicator( SetMap<Class<? extends IdentifiableObject>, IdentifiableObject> metadata, Indicator indicator )
{
if ( indicator == null ) return metadata;
metadata.putValue( Indicator.class, indicator );
handleIndicatorType( metadata, indicator.getIndicatorType() );
return metadata;
}
private SetMap<Class<? extends IdentifiableObject>, IdentifiableObject> handleIndicatorType( SetMap<Class<? extends IdentifiableObject>, IdentifiableObject> metadata, IndicatorType indicatorType )
{
if ( indicatorType == null ) return metadata;
metadata.putValue( IndicatorType.class, indicatorType );
return metadata;
}
private SetMap<Class<? extends IdentifiableObject>, IdentifiableObject> handleProgram( SetMap<Class<? extends IdentifiableObject>, IdentifiableObject> metadata, Program program )
{
if ( program == null ) return metadata;
metadata.putValue( Program.class, program );
handleCategoryCombo( metadata, program.getCategoryCombo() );
handleDataEntryForm( metadata, program.getDataEntryForm() );
handleTrackedEntity( metadata, program.getTrackedEntity() );
program.getProgramStages().forEach( programStage -> handleProgramStage( metadata, programStage ) );
program.getProgramAttributes().forEach( programTrackedEntityAttribute -> handleProgramTrackedEntityAttribute( metadata, programTrackedEntityAttribute ) );
program.getProgramIndicators().forEach( programIndicator -> handleProgramIndicator( metadata, programIndicator ) );
List<ProgramRule> programRules = programRuleService.getProgramRule( program );
List<ProgramRuleVariable> programRuleVariables = programRuleVariableService.getProgramRuleVariable( program );
programRules.forEach( programRule -> handleProgramRule( metadata, programRule ) );
programRuleVariables.forEach( programRuleVariable -> handleProgramRuleVariable( metadata, programRuleVariable ) );
return metadata;
}
private SetMap<Class<? extends IdentifiableObject>, IdentifiableObject> handleProgramRuleVariable( SetMap<Class<? extends IdentifiableObject>, IdentifiableObject> metadata, ProgramRuleVariable programRuleVariable )
{
if ( programRuleVariable == null ) return metadata;
metadata.putValue( ProgramRuleVariable.class, programRuleVariable );
handleTrackedEntityAttribute( metadata, programRuleVariable.getAttribute() );
handleDataElement( metadata, programRuleVariable.getDataElement() );
handleProgramStage( metadata, programRuleVariable.getProgramStage() );
return metadata;
}
private SetMap<Class<? extends IdentifiableObject>, IdentifiableObject> handleTrackedEntityAttribute( SetMap<Class<? extends IdentifiableObject>, IdentifiableObject> metadata, TrackedEntityAttribute trackedEntityAttribute )
{
if ( trackedEntityAttribute == null ) return metadata;
metadata.putValue( TrackedEntityAttribute.class, trackedEntityAttribute );
handleOptionSet( metadata, trackedEntityAttribute.getOptionSet() );
return metadata;
}
private SetMap<Class<? extends IdentifiableObject>, IdentifiableObject> handleProgramRule( SetMap<Class<? extends IdentifiableObject>, IdentifiableObject> metadata, ProgramRule programRule )
{
if ( programRule == null ) return metadata;
metadata.putValue( ProgramRule.class, programRule );
programRule.getProgramRuleActions().forEach( programRuleAction -> handleProgramRuleAction( metadata, programRuleAction ) );
return metadata;
}
private SetMap<Class<? extends IdentifiableObject>, IdentifiableObject> handleProgramRuleAction( SetMap<Class<? extends IdentifiableObject>, IdentifiableObject> metadata, ProgramRuleAction programRuleAction )
{
if ( programRuleAction == null ) return metadata;
metadata.putValue( ProgramRuleAction.class, programRuleAction );
handleDataElement( metadata, programRuleAction.getDataElement() );
handleTrackedEntityAttribute( metadata, programRuleAction.getAttribute() );
handleProgramIndicator( metadata, programRuleAction.getProgramIndicator() );
handleProgramStageSection( metadata, programRuleAction.getProgramStageSection() );
handleProgramStage( metadata, programRuleAction.getProgramStage() );
return metadata;
}
private SetMap<Class<? extends IdentifiableObject>, IdentifiableObject> handleProgramTrackedEntityAttribute( SetMap<Class<? extends IdentifiableObject>, IdentifiableObject> metadata, ProgramTrackedEntityAttribute programTrackedEntityAttribute )
{
if ( programTrackedEntityAttribute == null ) return metadata;
metadata.putValue( ProgramTrackedEntityAttribute.class, programTrackedEntityAttribute );
handleTrackedEntityAttribute( metadata, programTrackedEntityAttribute.getAttribute() );
return metadata;
}
private SetMap<Class<? extends IdentifiableObject>, IdentifiableObject> handleProgramStage( SetMap<Class<? extends IdentifiableObject>, IdentifiableObject> metadata, ProgramStage programStage )
{
if ( programStage == null ) return metadata;
metadata.putValue( ProgramStage.class, programStage );
programStage.getProgramStageDataElements().forEach( programStageDataElement -> handleProgramStageDataElement( metadata, programStageDataElement ) );
programStage.getProgramStageSections().forEach( programStageSection -> handleProgramStageSection( metadata, programStageSection ) );
handleDataEntryForm( metadata, programStage.getDataEntryForm() );
return metadata;
}
private SetMap<Class<? extends IdentifiableObject>, IdentifiableObject> handleProgramStageSection( SetMap<Class<? extends IdentifiableObject>, IdentifiableObject> metadata, ProgramStageSection programStageSection )
{
if ( programStageSection == null ) return metadata;
metadata.putValue( ProgramStageSection.class, programStageSection );
programStageSection.getProgramStageDataElements().forEach( programStageDataElement -> handleProgramStageDataElement( metadata, programStageDataElement ) );
programStageSection.getProgramIndicators().forEach( programIndicator -> handleProgramIndicator( metadata, programIndicator ) );
return metadata;
}
private SetMap<Class<? extends IdentifiableObject>, IdentifiableObject> handleProgramIndicator( SetMap<Class<? extends IdentifiableObject>, IdentifiableObject> metadata, ProgramIndicator programIndicator )
{
if ( programIndicator == null ) return metadata;
metadata.putValue( ProgramIndicator.class, programIndicator );
return metadata;
}
private SetMap<Class<? extends IdentifiableObject>, IdentifiableObject> handleProgramStageDataElement( SetMap<Class<? extends IdentifiableObject>, IdentifiableObject> metadata, ProgramStageDataElement programStageDataElement )
{
if ( programStageDataElement == null ) return metadata;
metadata.putValue( ProgramStageDataElement.class, programStageDataElement );
handleDataElement( metadata, programStageDataElement.getDataElement() );
return metadata;
}
private SetMap<Class<? extends IdentifiableObject>, IdentifiableObject> handleTrackedEntity( SetMap<Class<? extends IdentifiableObject>, IdentifiableObject> metadata, TrackedEntity trackedEntity )
{
if ( trackedEntity == null ) return metadata;
metadata.putValue( TrackedEntity.class, trackedEntity );
return metadata;
}
}
|
package edu.wustl.catissuecore.action;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import edu.wustl.catissuecore.actionForm.SimpleQueryInterfaceForm;
import edu.wustl.catissuecore.dao.DAOFactory;
import edu.wustl.catissuecore.dao.JDBCDAO;
import edu.wustl.catissuecore.util.global.Constants;
import edu.wustl.common.beans.NameValueBean;
import edu.wustl.common.util.dbManager.DAOException;
import edu.wustl.common.util.logger.Logger;
/**
* SimpleQueryInterfaceAction initializes the fields in the Simple Query Interface.
* @author gautam_shetty
*/
public class SimpleQueryInterfaceAction extends SecureAction
{
/**
* Overrides the execute method of Action class.
*/
public ActionForward executeSecureAction(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response) throws Exception
{
SimpleQueryInterfaceForm simpleQueryInterfaceForm = (SimpleQueryInterfaceForm) form;
int counter = Integer.parseInt(simpleQueryInterfaceForm.getCounter());
for (int i=1;i<=counter;i++)
{
//Key of previous object.
String prevKey = "SimpleConditionsNode:"+(i-1)+"_Condition_DataElement_table";
String prevValue = (String)simpleQueryInterfaceForm.getValue(prevKey);
//Key of present object.
String key = "SimpleConditionsNode:"+i+"_Condition_DataElement_table";
String value = (String)simpleQueryInterfaceForm.getValue(key);
//Key of the next operator (AND/OR).
String nextOperatorKey = "SimpleConditionsNode:"+i+"_Operator_operator";
String nextOperatorValue = (String)simpleQueryInterfaceForm.getValue(nextOperatorKey);
if (value != null)
{
if (!value.equals(Constants.SELECT_OPTION))
{
setColumnNames(request, i, value);
}
}
String sql = " select TABLE_A.ALIAS_NAME, TABLE_A.DISPLAY_NAME " +
" from catissue_table_relation TABLE_R, " +
" CATISSUE_QUERY_INTERFACE_TABLE_DATA TABLE_A, " +
" CATISSUE_QUERY_INTERFACE_TABLE_DATA TABLE_B " +
" where TABLE_R.PARENT_TABLE_ID = TABLE_A.TABLE_ID and " +
" TABLE_R.CHILD_TABLE_ID = TABLE_B.TABLE_ID ";
Logger.out.debug("Check sql....................."+sql);
JDBCDAO jdbcDao = (JDBCDAO)DAOFactory.getDAO(Constants.JDBC_DAO);
jdbcDao.openSession(null);
List checkList = jdbcDao.executeQuery(sql,null,Constants.INSECURE_RETRIEVE,null,null);
jdbcDao.closeSession();
if (i == counter)
{
if (prevValue != null)
setNextTableNames(request, i, prevValue, checkList);
else
setAllTableNames(request);
}
else
{
if (nextOperatorValue != null && !"".equals(nextOperatorValue))
{
String prevValueDisplayName = null;
String objectNameValueBeanList = "objectList"+i;
JDBCDAO jdbcDAO = (JDBCDAO)DAOFactory.getDAO(Constants.JDBC_DAO);
jdbcDAO.openSession(null);
sql = "select DISPLAY_NAME from CATISSUE_QUERY_INTERFACE_TABLE_DATA where ALIAS_NAME='"+value+"'";
List list = jdbcDAO.executeQuery(sql,null,Constants.INSECURE_RETRIEVE,null,null);
jdbcDAO.closeSession();
if (!list.isEmpty())
{
List rowList = (List)list.get(0);
prevValueDisplayName = (String)rowList.get(0);
}
NameValueBean nameValueBean = new NameValueBean();
nameValueBean.setName(prevValueDisplayName);
nameValueBean.setValue(value);
List objectList = new ArrayList();
objectList.add(nameValueBean);
request.setAttribute(objectNameValueBeanList, objectList);
}
}
}
request.setAttribute(Constants.ATTRIBUTE_NAME_LIST, Constants.ATTRIBUTE_NAME_ARRAY);
request.setAttribute(Constants.ATTRIBUTE_CONDITION_LIST, Constants.ATTRIBUTE_CONDITION_ARRAY);
HttpSession session =request.getSession();
session.setAttribute(Constants.SIMPLE_QUERY_ALIAS_NAME,null);
session.setAttribute(Constants.SIMPLE_QUERY_COUNTER,null);
session.setAttribute(Constants.SIMPLE_QUERY_MAP,null);
String pageOf = request.getParameter(Constants.PAGEOF);
request.setAttribute(Constants.PAGEOF, pageOf);
String target = Constants.PAGEOF_EDIT_OBJECT;
if (Constants.PAGEOF_SIMPLE_QUERY_INTERFACE.equals(pageOf))
target = Constants.PAGEOF_SIMPLE_QUERY_INTERFACE;
if(pageOf != null && pageOf.equals("pageOfSimpleQueryInterface" ) )
request.setAttribute("menuSelected",new String("17") );
return mapping.findForward(target);
}
/**
* Sets column names depending on the table name selected for that condition.
* @param request HttpServletRequest
* @param i number of row.
* @param value table name.
* @throws DAOException
* @throws ClassNotFoundException
*/
private void setColumnNames(HttpServletRequest request, int i, String value) throws DAOException, ClassNotFoundException
{
String attributeNameList = "attributeNameList"+i;
String attributeDisplayNameList = "attributeDisplayNameList"+i;
String sql = " SELECT tableData2.ALIAS_NAME, temp.COLUMN_NAME, temp.ATTRIBUTE_TYPE, temp.TABLES_IN_PATH, temp.DISPLAY_NAME " +
" from CATISSUE_QUERY_INTERFACE_TABLE_DATA tableData2 join " +
" ( SELECT columnData.COLUMN_NAME, columnData.TABLE_ID, columnData.ATTRIBUTE_TYPE, " +
" displayData.DISPLAY_NAME, relationData.TABLES_IN_PATH " +
" FROM CATISSUE_QUERY_INTERFACE_COLUMN_DATA columnData, " +
" CATISSUE_TABLE_RELATION relationData, " +
" CATISSUE_QUERY_INTERFACE_TABLE_DATA tableData, " +
" CATISSUE_SEARCH_DISPLAY_DATA displayData " +
" where relationData.CHILD_TABLE_ID = columnData.TABLE_ID and " +
" relationData.PARENT_TABLE_ID = tableData.TABLE_ID and " +
" relationData.RELATIONSHIP_ID = displayData.RELATIONSHIP_ID and " +
" columnData.IDENTIFIER = displayData.COL_ID and " +
" tableData.ALIAS_NAME = '"+value+"') as temp " +
" on temp.TABLE_ID = tableData2.TABLE_ID ";
Logger.out.debug("SQL*****************************"+sql);
JDBCDAO jdbcDao = new JDBCDAO();
jdbcDao.openSession(null);
List list = jdbcDao.executeQuery(sql, null, Constants.INSECURE_RETRIEVE, null,null);
jdbcDao.closeSession();
String [] columnNameList = new String[list.size()];
String [] columnDisplayNameList = new String[list.size()];
Iterator iterator = list.iterator();
int j = 0, k=0;
while (iterator.hasNext())
{
List rowList = (List)iterator.next();
columnNameList[k] = (String)rowList.get(j++)+"."+(String)rowList.get(j++)
+"."+(String)rowList.get(j++);
String tablesInPath = (String)rowList.get(j++);
if ((tablesInPath != null) && ("".equals(tablesInPath) == false))
{
columnNameList[k] = columnNameList[k]+"."+tablesInPath;
}
columnDisplayNameList[k] = (String)rowList.get(j++);
j = 0;
k++;
}
request.setAttribute(attributeNameList, columnNameList);
request.setAttribute(attributeDisplayNameList, columnDisplayNameList);
}
/**
* Sets the next table names depending on the table in the previous row.
* @param request
* @param i
* @param prevValue previous table name.
* @param nextOperatorValue
* @param checkList
* @throws DAOException
* @throws ClassNotFoundException
*/
private void setNextTableNames(HttpServletRequest request, int i, String prevValue, List checkList) throws DAOException, ClassNotFoundException
{
String objectNameList = "objectList"+i;
List objectList = new ArrayList();
String sql =" (select temp.ALIAS_NAME, temp.DISPLAY_NAME " +
" from " +
" (select relationData.FIRST_TABLE_ID, tableData.ALIAS_NAME, tableData.DISPLAY_NAME " +
" from CATISSUE_QUERY_INTERFACE_TABLE_DATA tableData join " +
" CATISSUE_RELATED_TABLES_MAP relationData " +
" on tableData.TABLE_ID = relationData.SECOND_TABLE_ID) as temp join CATISSUE_QUERY_INTERFACE_TABLE_DATA tableData2 " +
" on temp.FIRST_TABLE_ID = tableData2.TABLE_ID " +
" where tableData2.ALIAS_NAME = '"+prevValue+"') " +
" union " +
" (select temp1.ALIAS_NAME, temp1.DISPLAY_NAME " +
" from " +
" (select relationData1.SECOND_TABLE_ID, tableData4.ALIAS_NAME, tableData4.DISPLAY_NAME " +
" from CATISSUE_QUERY_INTERFACE_TABLE_DATA tableData4 join " +
" CATISSUE_RELATED_TABLES_MAP relationData1 " +
" on tableData4.TABLE_ID = relationData1.FIRST_TABLE_ID) as temp1 join CATISSUE_QUERY_INTERFACE_TABLE_DATA tableData3 " +
" on temp1.SECOND_TABLE_ID = tableData3.TABLE_ID " +
" where tableData3.ALIAS_NAME = '"+prevValue+"')";
Logger.out.debug("TABLE SQL*****************************"+sql);
JDBCDAO jdbcDao = (JDBCDAO)DAOFactory.getDAO(Constants.JDBC_DAO);
jdbcDao.openSession(null);
List list = jdbcDao.executeQuery(sql,null,Constants.INSECURE_RETRIEVE,null,null);
jdbcDao.closeSession();
//Adding NameValueBean of select option.
NameValueBean nameValueBean = new NameValueBean();
nameValueBean.setName(Constants.SELECT_OPTION);
nameValueBean.setValue("-1");
objectList.add(nameValueBean);
//Adding the NameValueBean of previous selected object.
JDBCDAO jdbcDAO = (JDBCDAO)DAOFactory.getDAO(Constants.JDBC_DAO);
jdbcDAO.openSession(null);
sql = "select DISPLAY_NAME from CATISSUE_QUERY_INTERFACE_TABLE_DATA where ALIAS_NAME='"+prevValue+"'";
List prevValueDisplayNameList = jdbcDAO.executeQuery(sql,null,Constants.INSECURE_RETRIEVE,null,null);
jdbcDAO.closeSession();
if (!prevValueDisplayNameList.isEmpty())
{
List rowList = (List)prevValueDisplayNameList.get(0);
nameValueBean = new NameValueBean();
nameValueBean.setName((String)rowList.get(0));
nameValueBean.setValue(prevValue);
objectList.add(nameValueBean);
}
Iterator iterator = list.iterator();
while (iterator.hasNext())
{
int j=0;
List rowList = (List)iterator.next();
if (checkForTable(rowList, checkList))
{
nameValueBean = new NameValueBean();
nameValueBean.setValue((String)rowList.get(j++));
nameValueBean.setName((String)rowList.get(j));
objectList.add(nameValueBean);
}
}
request.setAttribute(objectNameList, objectList);
}
/**
* Returns the object id of the protection element that represents
* the Action that is being requested for invocation.
* @param clazz
* @return
*/
protected String getObjectIdForSecureMethodAccess(HttpServletRequest request)
{
String aliasName = request.getParameter("aliasName");
if(aliasName!=null && !aliasName.equals(""))
{
return this.getClass().getName()+"_"+aliasName;
}
else
{
return super.getObjectIdForSecureMethodAccess(request);
}
}
/**
* @param mapping
* @return
*/
protected ActionForward getActionForward(HttpServletRequest request,ActionMapping mapping)
{
String aliasName = request.getParameter("aliasName");
if(aliasName.equals("User") || aliasName.equals("Institution") || aliasName.equals("Department")|| aliasName.equals("CancerResearchGroup")|| aliasName.equals("Site")|| aliasName.equals("StorageType")|| aliasName.equals("StorageContainer")|| aliasName.equals("BioHazard")|| aliasName.equals("CollectionProtocol")|| aliasName.equals("DistributionProtocol"))
{
return mapping.findForward(Constants.ACCESS_DENIED_ADMIN);
}
else if(aliasName.equals("Participant") ||aliasName.equals("CollectionProtocolRegistration") ||aliasName.equals("SpecimenCollectionGroup") ||aliasName.equals("Specimen") ||aliasName.equals("Distribution"))
{
return mapping.findForward(Constants.ACCESS_DENIED_BIOSPECIMEN);
}
else
{
return mapping.findForward(Constants.ACCESS_DENIED);
}
}
private boolean checkForTable(List rowList, List checkList)
{
String aliasName = (String)rowList.get(0), displayName = (String)rowList.get(1);
Iterator iterator = checkList.iterator();
while (iterator.hasNext())
{
List row = (List) iterator.next();
if (aliasName.equals((String) row.get(0)) && displayName.equals((String) row.get(1)))
{
return true;
}
}
return false;
}
/**
* Sets all the tables in the simple query interface.
* @param request
* @throws DAOException
* @throws ClassNotFoundException
*/
private void setAllTableNames(HttpServletRequest request)throws DAOException, ClassNotFoundException
{
String sql = " select distinct tableData.DISPLAY_NAME, tableData.ALIAS_NAME " +
" from CATISSUE_TABLE_RELATION tableRelation join CATISSUE_QUERY_INTERFACE_TABLE_DATA " +
" tableData on tableRelation.PARENT_TABLE_ID = tableData.TABLE_ID ";
String aliasName = request.getParameter(Constants.TABLE_ALIAS_NAME);
if ((aliasName != null) && (!"".equals(aliasName)))
{
sql = sql + " where tableData.ALIAS_NAME = '"+ aliasName +"'";
request.setAttribute(Constants.TABLE_ALIAS_NAME,aliasName);
}
sql = sql + " ORDER BY tableData.DISPLAY_NAME ";
JDBCDAO jdbcDAO = (JDBCDAO)DAOFactory.getDAO(Constants.JDBC_DAO);
jdbcDAO.openSession(null);
List tableList = jdbcDAO.executeQuery(sql,null,Constants.INSECURE_RETRIEVE,null,null);
jdbcDAO.closeSession();
String [] objectDisplayNames = null;
String [] objectAliasNames = null;
int i = 0;
if ((aliasName != null) && (!"".equals(aliasName)))
{
objectDisplayNames = new String[tableList.size()];
objectAliasNames = new String[tableList.size()];
setColumnNames(request,1,aliasName);
}
else
{
objectDisplayNames = new String[tableList.size()+1];
objectAliasNames = new String[tableList.size()+1];
objectAliasNames[i] = "-1";
objectDisplayNames[i] = Constants.SELECT_OPTION;
i++;
}
Iterator objIterator = tableList.iterator();
while (objIterator.hasNext())
{
List row = (List) objIterator.next();
objectDisplayNames[i] = (String)row.get(0);
objectAliasNames[i] = (String)row.get(1);
i++;
}
request.setAttribute(Constants.OBJECT_DISPLAY_NAME_LIST, objectDisplayNames);
request.setAttribute(Constants.OBJECT_ALIAS_NAME_LIST, objectAliasNames);
}
}
|
package org.jfree.text;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics2D;
import java.awt.Paint;
import java.awt.Shape;
import java.awt.font.FontRenderContext;
import java.awt.font.LineMetrics;
import java.awt.font.TextLayout;
import java.awt.geom.AffineTransform;
import java.awt.geom.Rectangle2D;
import java.text.AttributedString;
import java.text.BreakIterator;
import org.jfree.base.BaseBoot;
import org.jfree.ui.TextAnchor;
import org.jfree.util.Log;
import org.jfree.util.LogContext;
import org.jfree.util.ObjectUtilities;
/**
* Some utility methods for working with text in Java2D.
*/
public class TextUtilities {
/** Access to logging facilities. */
protected static final LogContext logger = Log.createContext(
TextUtilities.class);
/**
* A flag that controls whether or not the rotated string workaround is
* used.
*/
private static boolean useDrawRotatedStringWorkaround;
/**
* A flag that controls whether the FontMetrics.getStringBounds() method
* is used or a workaround is applied.
*/
private static boolean useFontMetricsGetStringBounds;
static {
try {
boolean isJava14 = ObjectUtilities.isJDK14();
String configRotatedStringWorkaround = BaseBoot.getInstance()
.getGlobalConfig().getConfigProperty(
"org.jfree.text.UseDrawRotatedStringWorkaround", "auto");
if (configRotatedStringWorkaround.equals("auto")) {
useDrawRotatedStringWorkaround = !isJava14;
}
else {
useDrawRotatedStringWorkaround
= configRotatedStringWorkaround.equals("true");
}
String configFontMetricsStringBounds = BaseBoot.getInstance()
.getGlobalConfig().getConfigProperty(
"org.jfree.text.UseFontMetricsGetStringBounds", "auto");
if (configFontMetricsStringBounds.equals("auto")) {
useFontMetricsGetStringBounds = isJava14;
} else {
useFontMetricsGetStringBounds
= configFontMetricsStringBounds.equals("true");
}
}
catch (Exception e) {
// ignore everything.
useDrawRotatedStringWorkaround = true;
useFontMetricsGetStringBounds = true;
}
}
/**
* Private constructor prevents object creation.
*/
private TextUtilities() {
// prevent instantiation
}
/**
* Creates a {@link TextBlock} from a <code>String</code>. Line breaks
* are added where the <code>String</code> contains '\n' characters.
*
* @param text the text.
* @param font the font.
* @param paint the paint.
*
* @return A text block.
*/
public static TextBlock createTextBlock(String text, Font font,
Paint paint) {
if (text == null) {
throw new IllegalArgumentException("Null 'text' argument.");
}
TextBlock result = new TextBlock();
String input = text;
boolean moreInputToProcess = (text.length() > 0);
int start = 0;
while (moreInputToProcess) {
int index = input.indexOf("\n");
if (index > start) {
String line = input.substring(start, index);
if (index < input.length() - 1) {
result.addLine(line, font, paint);
input = input.substring(index + 1);
}
else {
moreInputToProcess = false;
}
}
else if (index == start) {
if (index < input.length() - 1) {
input = input.substring(index + 1);
}
else {
moreInputToProcess = false;
}
}
else {
result.addLine(input, font, paint);
moreInputToProcess = false;
}
}
return result;
}
/**
* Creates a new text block from the given string, breaking the
* text into lines so that the <code>maxWidth</code> value is
* respected.
*
* @param text the text.
* @param font the font.
* @param paint the paint.
* @param maxWidth the maximum width for each line.
* @param measurer the text measurer.
*
* @return A text block.
*/
public static TextBlock createTextBlock(String text, Font font,
Paint paint, float maxWidth, TextMeasurer measurer) {
return createTextBlock(text, font, paint, maxWidth, Integer.MAX_VALUE,
measurer);
}
/**
* Creates a new text block from the given string, breaking the
* text into lines so that the <code>maxWidth</code> value is
* respected.
*
* @param text the text.
* @param font the font.
* @param paint the paint.
* @param maxWidth the maximum width for each line.
* @param maxLines the maximum number of lines.
* @param measurer the text measurer.
*
* @return A text block.
*/
public static TextBlock createTextBlock(String text, Font font,
Paint paint, float maxWidth, int maxLines, TextMeasurer measurer) {
TextBlock result = new TextBlock();
BreakIterator iterator = BreakIterator.getLineInstance();
iterator.setText(text);
int current = 0;
int lines = 0;
int length = text.length();
while (current < length && lines < maxLines) {
int next = nextLineBreak(text, current, maxWidth, iterator,
measurer);
if (next == BreakIterator.DONE) {
result.addLine(text.substring(current), font, paint);
return result;
}
result.addLine(text.substring(current, next), font, paint);
lines++;
current = next;
while (current < text.length()&& text.charAt(current) == '\n') {
current++;
}
}
if (current < length) {
TextLine lastLine = result.getLastLine();
TextFragment lastFragment = lastLine.getLastTextFragment();
String oldStr = lastFragment.getText();
String newStr = "...";
if (oldStr.length() > 3) {
newStr = oldStr.substring(0, oldStr.length() - 3) + "...";
}
lastLine.removeFragment(lastFragment);
TextFragment newFragment = new TextFragment(newStr,
lastFragment.getFont(), lastFragment.getPaint());
lastLine.addFragment(newFragment);
}
return result;
}
/**
* Returns the character index of the next line break.
*
* @param text the text (<code>null</code> not permitted).
* @param start the start index.
* @param width the target display width.
* @param iterator the word break iterator.
* @param measurer the text measurer.
*
* @return The index of the next line break.
*/
private static int nextLineBreak(String text, int start, float width,
BreakIterator iterator, TextMeasurer measurer) {
// this method is (loosely) based on code in JFreeReport's
// TextParagraph class
int current = start;
int end;
float x = 0.0f;
boolean firstWord = true;
int newline = text.indexOf('\n', start);
if (newline < 0) {
newline = Integer.MAX_VALUE;
}
while (((end = iterator.following(current)) != BreakIterator.DONE)) {
x += measurer.getStringWidth(text, current, end);
if (x > width) {
if (firstWord) {
while (measurer.getStringWidth(text, start, end) > width) {
end
if (end <= start) {
return end;
}
}
return end;
}
else {
end = iterator.previous();
return end;
}
}
else {
if (end > newline) {
return newline;
}
}
// we found at least one word that fits ...
firstWord = false;
current = end;
}
return BreakIterator.DONE;
}
/**
* Returns the bounds for the specified text.
*
* @param text the text (<code>null</code> permitted).
* @param g2 the graphics context (not <code>null</code>).
* @param fm the font metrics (not <code>null</code>).
*
* @return The text bounds (<code>null</code> if the <code>text</code>
* argument is <code>null</code>).
*/
public static Rectangle2D getTextBounds(String text, Graphics2D g2,
FontMetrics fm) {
Rectangle2D bounds;
if (TextUtilities.useFontMetricsGetStringBounds) {
bounds = fm.getStringBounds(text, g2);
// getStringBounds() can return incorrect height for some Unicode
// characters...see bug parade 6183356, let's replace it with
// something correct
LineMetrics lm = fm.getFont().getLineMetrics(text,
g2.getFontRenderContext());
bounds.setRect(bounds.getX(), bounds.getY(), bounds.getWidth(),
lm.getHeight());
}
else {
double width = fm.stringWidth(text);
double height = fm.getHeight();
if (logger.isDebugEnabled()) {
logger.debug("Height = " + height);
}
bounds = new Rectangle2D.Double(0.0, -fm.getAscent(), width,
height);
}
return bounds;
}
/**
* Draws a string such that the specified anchor point is aligned to the
* given (x, y) location.
*
* @param text the text.
* @param g2 the graphics device.
* @param x the x coordinate (Java 2D).
* @param y the y coordinate (Java 2D).
* @param anchor the anchor location.
*
* @return The text bounds (adjusted for the text position).
*/
public static Rectangle2D drawAlignedString(String text, Graphics2D g2,
float x, float y, TextAnchor anchor) {
Rectangle2D textBounds = new Rectangle2D.Double();
float[] adjust = deriveTextBoundsAnchorOffsets(g2, text, anchor,
textBounds);
// adjust text bounds to match string position
textBounds.setRect(x + adjust[0], y + adjust[1] + adjust[2],
textBounds.getWidth(), textBounds.getHeight());
g2.drawString(text, x + adjust[0], y + adjust[1]);
return textBounds;
}
/**
* A utility method that calculates the anchor offsets for a string.
* Normally, the (x, y) coordinate for drawing text is a point on the
* baseline at the left of the text string. If you add these offsets to
* (x, y) and draw the string, then the anchor point should coincide with
* the (x, y) point.
*
* @param g2 the graphics device (not <code>null</code>).
* @param text the text.
* @param anchor the anchor point.
* @param textBounds the text bounds (if not <code>null</code>, this
* object will be updated by this method to match the
* string bounds).
*
* @return The offsets.
*/
private static float[] deriveTextBoundsAnchorOffsets(Graphics2D g2,
String text, TextAnchor anchor, Rectangle2D textBounds) {
float[] result = new float[3];
FontRenderContext frc = g2.getFontRenderContext();
Font f = g2.getFont();
FontMetrics fm = g2.getFontMetrics(f);
Rectangle2D bounds = TextUtilities.getTextBounds(text, g2, fm);
LineMetrics metrics = f.getLineMetrics(text, frc);
float ascent = metrics.getAscent();
result[2] = -ascent;
float halfAscent = ascent / 2.0f;
float descent = metrics.getDescent();
float leading = metrics.getLeading();
float xAdj = 0.0f;
float yAdj = 0.0f;
if (anchor.isHorizontalCenter()) {
xAdj = (float) -bounds.getWidth() / 2.0f;
}
else if (anchor.isRight()) {
xAdj = (float) -bounds.getWidth();
}
if (anchor.isTop()) {
yAdj = -descent - leading + (float) bounds.getHeight();
}
else if (anchor.isHalfAscent()) {
yAdj = halfAscent;
}
else if (anchor.isVerticalCenter()) {
yAdj = -descent - leading + (float) (bounds.getHeight() / 2.0);
}
else if (anchor.isBaseline()) {
yAdj = 0.0f;
}
else if (anchor.isBottom()) {
yAdj = -metrics.getDescent() - metrics.getLeading();
}
if (textBounds != null) {
textBounds.setRect(bounds);
}
result[0] = xAdj;
result[1] = yAdj;
return result;
}
/**
* A utility method for drawing rotated text.
* <P>
* A common rotation is -Math.PI/2 which draws text 'vertically' (with the
* top of the characters on the left).
*
* @param text the text.
* @param g2 the graphics device.
* @param angle the angle of the (clockwise) rotation (in radians).
* @param x the x-coordinate.
* @param y the y-coordinate.
*/
public static void drawRotatedString(String text, Graphics2D g2,
double angle, float x, float y) {
drawRotatedString(text, g2, x, y, angle, x, y);
}
/**
* A utility method for drawing rotated text.
* <P>
* A common rotation is -Math.PI/2 which draws text 'vertically' (with the
* top of the characters on the left).
*
* @param text the text.
* @param g2 the graphics device.
* @param textX the x-coordinate for the text (before rotation).
* @param textY the y-coordinate for the text (before rotation).
* @param angle the angle of the (clockwise) rotation (in radians).
* @param rotateX the point about which the text is rotated.
* @param rotateY the point about which the text is rotated.
*/
public static void drawRotatedString(String text, Graphics2D g2,
float textX, float textY,
double angle, float rotateX, float rotateY) {
if ((text == null) || (text.equals(""))) {
return;
}
if (angle == 0.0) {
drawAlignedString(text, g2, textY, textY, TextAnchor.BASELINE_LEFT);
return;
}
AffineTransform saved = g2.getTransform();
AffineTransform rotate = AffineTransform.getRotateInstance(
angle, rotateX, rotateY);
g2.transform(rotate);
if (useDrawRotatedStringWorkaround) {
// workaround for JDC bug ID 4312117 and others...
TextLayout tl = new TextLayout(text, g2.getFont(),
g2.getFontRenderContext());
tl.draw(g2, textX, textY);
}
else {
AttributedString as = new AttributedString(text,
g2.getFont().getAttributes());
g2.drawString(as.getIterator(), textX, textY);
}
g2.setTransform(saved);
}
/**
* Draws a string that is aligned by one anchor point and rotated about
* another anchor point.
*
* @param text the text.
* @param g2 the graphics device.
* @param x the x-coordinate for positioning the text.
* @param y the y-coordinate for positioning the text.
* @param textAnchor the text anchor.
* @param angle the rotation angle.
* @param rotationX the x-coordinate for the rotation anchor point.
* @param rotationY the y-coordinate for the rotation anchor point.
*/
public static void drawRotatedString(String text, Graphics2D g2,
float x, float y, TextAnchor textAnchor,
double angle, float rotationX, float rotationY) {
if (text == null || text.equals("")) {
return;
}
if (angle == 0.0) {
drawAlignedString(text, g2, x, y, textAnchor);
} else {
float[] textAdj = deriveTextBoundsAnchorOffsets(g2, text,
textAnchor);
drawRotatedString(text, g2, x + textAdj[0], y + textAdj[1], angle,
rotationX, rotationY);
}
}
/**
* Draws a string that is aligned by one anchor point and rotated about
* another anchor point.
*
* @param text the text.
* @param g2 the graphics device.
* @param x the x-coordinate for positioning the text.
* @param y the y-coordinate for positioning the text.
* @param textAnchor the text anchor.
* @param angle the rotation angle (in radians).
* @param rotationAnchor the rotation anchor.
*/
public static void drawRotatedString(String text, Graphics2D g2,
float x, float y, TextAnchor textAnchor,
double angle, TextAnchor rotationAnchor) {
if (text == null || text.equals("")) {
return;
}
if (angle == 0.0) {
drawAlignedString(text, g2, x, y, textAnchor);
} else {
float[] textAdj = deriveTextBoundsAnchorOffsets(g2, text,
textAnchor);
float[] rotateAdj = deriveRotationAnchorOffsets(g2, text,
rotationAnchor);
drawRotatedString(text, g2, x + textAdj[0], y + textAdj[1],
angle, x + textAdj[0] + rotateAdj[0],
y + textAdj[1] + rotateAdj[1]);
}
}
/**
* Returns a shape that represents the bounds of the string after the
* specified rotation has been applied.
*
* @param text the text (<code>null</code> permitted).
* @param g2 the graphics device.
* @param x the x coordinate for the anchor point.
* @param y the y coordinate for the anchor point.
* @param textAnchor the text anchor.
* @param angle the angle.
* @param rotationAnchor the rotation anchor.
*
* @return The bounds (possibly <code>null</code>).
*/
public static Shape calculateRotatedStringBounds(String text, Graphics2D g2,
float x, float y, TextAnchor textAnchor,
double angle, TextAnchor rotationAnchor) {
if (text == null || text.equals("")) {
return null;
}
float[] textAdj = deriveTextBoundsAnchorOffsets(g2, text, textAnchor);
if (logger.isDebugEnabled()) {
logger.debug("TextBoundsAnchorOffsets = " + textAdj[0] + ", "
+ textAdj[1]);
}
float[] rotateAdj = deriveRotationAnchorOffsets(g2, text,
rotationAnchor);
if (logger.isDebugEnabled()) {
logger.debug("RotationAnchorOffsets = " + rotateAdj[0] + ", "
+ rotateAdj[1]);
}
Shape result = calculateRotatedStringBounds(text, g2,
x + textAdj[0], y + textAdj[1], angle,
x + textAdj[0] + rotateAdj[0], y + textAdj[1] + rotateAdj[1]);
return result;
}
/**
* A utility method that calculates the anchor offsets for a string.
* Normally, the (x, y) coordinate for drawing text is a point on the
* baseline at the left of the text string. If you add these offsets to
* (x, y) and draw the string, then the anchor point should coincide with
* the (x, y) point.
*
* @param g2 the graphics device (not <code>null</code>).
* @param text the text.
* @param anchor the anchor point.
*
* @return The offsets.
*/
private static float[] deriveTextBoundsAnchorOffsets(Graphics2D g2,
String text, TextAnchor anchor) {
float[] result = new float[2];
FontRenderContext frc = g2.getFontRenderContext();
Font f = g2.getFont();
FontMetrics fm = g2.getFontMetrics(f);
Rectangle2D bounds = TextUtilities.getTextBounds(text, g2, fm);
LineMetrics metrics = f.getLineMetrics(text, frc);
float ascent = metrics.getAscent();
float halfAscent = ascent / 2.0f;
float descent = metrics.getDescent();
float leading = metrics.getLeading();
float xAdj = 0.0f;
float yAdj = 0.0f;
if (anchor.isHorizontalCenter()) {
xAdj = (float) -bounds.getWidth() / 2.0f;
}
else if (anchor.isRight()) {
xAdj = (float) -bounds.getWidth();
}
if (anchor.isTop()) {
yAdj = -descent - leading + (float) bounds.getHeight();
}
else if (anchor.isHalfAscent()) {
yAdj = halfAscent;
}
else if (anchor.isVerticalCenter()) {
yAdj = -descent - leading + (float) (bounds.getHeight() / 2.0);
}
else if (anchor.isBaseline()) {
yAdj = 0.0f;
}
else if (anchor.isBottom()) {
yAdj = -metrics.getDescent() - metrics.getLeading();
}
result[0] = xAdj;
result[1] = yAdj;
return result;
}
/**
* A utility method that calculates the rotation anchor offsets for a
* string. These offsets are relative to the text starting coordinate
* (<code>BASELINE_LEFT</code>).
*
* @param g2 the graphics device.
* @param text the text.
* @param anchor the anchor point.
*
* @return The offsets.
*/
private static float[] deriveRotationAnchorOffsets(Graphics2D g2,
String text, TextAnchor anchor) {
float[] result = new float[2];
FontRenderContext frc = g2.getFontRenderContext();
LineMetrics metrics = g2.getFont().getLineMetrics(text, frc);
FontMetrics fm = g2.getFontMetrics();
Rectangle2D bounds = TextUtilities.getTextBounds(text, g2, fm);
float ascent = metrics.getAscent();
float halfAscent = ascent / 2.0f;
float descent = metrics.getDescent();
float leading = metrics.getLeading();
float xAdj = 0.0f;
float yAdj = 0.0f;
if (anchor.isLeft()) {
xAdj = 0.0f;
}
else if (anchor.isHorizontalCenter()) {
xAdj = (float) bounds.getWidth() / 2.0f;
}
else if (anchor.isRight()) {
xAdj = (float) bounds.getWidth();
}
if (anchor.isTop()) {
yAdj = descent + leading - (float) bounds.getHeight();
}
else if (anchor.isVerticalCenter()) {
yAdj = descent + leading - (float) (bounds.getHeight() / 2.0);
}
else if (anchor.isHalfAscent()) {
yAdj = -halfAscent;
}
else if (anchor.isBaseline()) {
yAdj = 0.0f;
}
else if (anchor.isBottom()) {
yAdj = metrics.getDescent() + metrics.getLeading();
}
result[0] = xAdj;
result[1] = yAdj;
return result;
}
/**
* Returns a shape that represents the bounds of the string after the
* specified rotation has been applied.
*
* @param text the text (<code>null</code> permitted).
* @param g2 the graphics device.
* @param textX the x coordinate for the text.
* @param textY the y coordinate for the text.
* @param angle the angle.
* @param rotateX the x coordinate for the rotation point.
* @param rotateY the y coordinate for the rotation point.
*
* @return The bounds (<code>null</code> if <code>text</code> is
* </code>null</code> or has zero length).
*/
public static Shape calculateRotatedStringBounds(String text, Graphics2D g2,
float textX, float textY, double angle, float rotateX,
float rotateY) {
if ((text == null) || (text.equals(""))) {
return null;
}
FontMetrics fm = g2.getFontMetrics();
Rectangle2D bounds = TextUtilities.getTextBounds(text, g2, fm);
AffineTransform translate = AffineTransform.getTranslateInstance(
textX, textY);
Shape translatedBounds = translate.createTransformedShape(bounds);
AffineTransform rotate = AffineTransform.getRotateInstance(
angle, rotateX, rotateY);
Shape result = rotate.createTransformedShape(translatedBounds);
return result;
}
/**
* Returns the flag that controls whether the FontMetrics.getStringBounds()
* method is used or not. If you are having trouble with label alignment
* or positioning, try changing the value of this flag.
*
* @return A boolean.
*/
public static boolean getUseFontMetricsGetStringBounds() {
return useFontMetricsGetStringBounds;
}
/**
* Sets the flag that controls whether the FontMetrics.getStringBounds()
* method is used or not. If you are having trouble with label alignment
* or positioning, try changing the value of this flag.
*
* @param use the flag.
*/
public static void setUseFontMetricsGetStringBounds(boolean use) {
useFontMetricsGetStringBounds = use;
}
/**
* Returns the flag that controls whether or not a workaround is used for
* drawing rotated strings.
*
* @return A boolean.
*/
public static boolean isUseDrawRotatedStringWorkaround() {
return useDrawRotatedStringWorkaround;
}
/**
* Sets the flag that controls whether or not a workaround is used for
* drawing rotated strings. The related bug is on Sun's bug parade
* (id 4312117) and the workaround involves using a <code>TextLayout</code>
* instance to draw the text instead of calling the
* <code>drawString()</code> method in the <code>Graphics2D</code> class.
*
* @param use the new flag value.
*/
public static void setUseDrawRotatedStringWorkaround(final boolean use) {
useDrawRotatedStringWorkaround = use;
}
}
|
package org.eclipse.birt.report.engine.presentation;
import java.io.BufferedInputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.ref.SoftReference;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Locale;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.eclipse.birt.core.exception.BirtException;
import org.eclipse.birt.core.format.DateFormatter;
import org.eclipse.birt.core.format.NumberFormatter;
import org.eclipse.birt.core.format.StringFormatter;
import org.eclipse.birt.core.template.TextTemplate;
import org.eclipse.birt.data.engine.api.IBaseQueryDefinition;
import org.eclipse.birt.report.engine.api.CachedImage;
import org.eclipse.birt.report.engine.api.EngineConstants;
import org.eclipse.birt.report.engine.api.IHTMLImageHandler;
import org.eclipse.birt.report.engine.api.IImage;
import org.eclipse.birt.report.engine.api.IRenderOption;
import org.eclipse.birt.report.engine.content.ContentVisitorAdapter;
import org.eclipse.birt.report.engine.content.ICellContent;
import org.eclipse.birt.report.engine.content.IContent;
import org.eclipse.birt.report.engine.content.IDataContent;
import org.eclipse.birt.report.engine.content.IForeignContent;
import org.eclipse.birt.report.engine.content.IImageContent;
import org.eclipse.birt.report.engine.content.ILabelContent;
import org.eclipse.birt.report.engine.content.IListContent;
import org.eclipse.birt.report.engine.content.IPageContent;
import org.eclipse.birt.report.engine.content.IReportContent;
import org.eclipse.birt.report.engine.content.IRowContent;
import org.eclipse.birt.report.engine.content.IStyle;
import org.eclipse.birt.report.engine.content.ITableContent;
import org.eclipse.birt.report.engine.content.ITextContent;
import org.eclipse.birt.report.engine.css.engine.value.css.CSSValueConstants;
import org.eclipse.birt.report.engine.executor.ExecutionContext;
import org.eclipse.birt.report.engine.executor.template.TemplateExecutor;
import org.eclipse.birt.report.engine.extension.IBaseResultSet;
import org.eclipse.birt.report.engine.extension.IQueryResultSet;
import org.eclipse.birt.report.engine.extension.IReportItemPresentation;
import org.eclipse.birt.report.engine.extension.IRowSet;
import org.eclipse.birt.report.engine.extension.internal.ExtensionManager;
import org.eclipse.birt.report.engine.extension.internal.RowSet;
import org.eclipse.birt.report.engine.extension.internal.SingleRowSet;
import org.eclipse.birt.report.engine.ir.ExtendedItemDesign;
import org.eclipse.birt.report.engine.ir.ListItemDesign;
import org.eclipse.birt.report.engine.ir.ReportItemDesign;
import org.eclipse.birt.report.engine.ir.TextItemDesign;
import org.eclipse.birt.report.engine.script.internal.OnRenderScriptVisitor;
import org.eclipse.birt.report.model.api.DesignElementHandle;
import org.eclipse.birt.report.model.api.ExtendedItemHandle;
import org.eclipse.birt.report.model.api.ModuleUtil;
import org.eclipse.birt.report.model.api.ReportDesignHandle;
import org.eclipse.birt.report.model.api.ReportElementHandle;
import org.w3c.dom.css.CSSValue;
import com.ibm.icu.util.ULocale;
public class LocalizedContentVisitor extends ContentVisitorAdapter
{
protected static Logger logger = Logger
.getLogger( LocalizedContentVisitor.class.getName( ) );
private ExecutionContext context;
private Locale locale;
private String outputFormat;
protected HashMap templates = new HashMap( );
private OnRenderScriptVisitor onRenderVisitor;
public LocalizedContentVisitor( ExecutionContext context )
{
this.context = context;
this.locale = context.getLocale( );
this.outputFormat = context.getOutputFormat( );
this.onRenderVisitor = new OnRenderScriptVisitor( context );
}
IReportContent getReportContent( )
{
return context.getReportContent( );
}
ReportDesignHandle getReportDesign( )
{
return context.getDesign( );
}
public IContent localize(IContent content)
{
Object value = content.accept( this, content );
return (IContent) value;
}
protected IContent localizeAllChildren( IContent content )
{
ArrayList children = (ArrayList) content.getChildren( );
if ( children != null )
{
for ( int i = 0; i < children.size( ); i++ )
{
IContent child = (IContent) children.get( i );
IContent localChild = localize( child );
if ( localChild != child )
{
// replace the child with the licallized child.
children.set( i, localChild );
// set the locallized child's parent as orient child's
// parent.
localChild.setParent( content );
// copy all children of this child to its localized child,
// also change all children's parent to this localized
// child.
Collection childrenOfLocalChild = localChild.getChildren( );
Iterator iter = child.getChildren( ).iterator( );
while ( iter.hasNext( ) )
{
IContent childOfChild = (IContent) iter.next( );
if ( !childrenOfLocalChild.contains( childOfChild ) )
{
childOfChild.setParent( localChild );
childrenOfLocalChild.add( childOfChild );
}
}
}
localizeAllChildren( localChild );
}
}
return content;
}
public Object visitPage( IPageContent page, Object value )
{
return page;
}
protected TextTemplate parseTemplate( String text )
{
SoftReference templateRef = (SoftReference) templates.get( text );
TextTemplate template = null;
if ( templateRef != null )
{
template = (TextTemplate) templateRef.get( );
if ( template != null )
{
return template;
}
}
try
{
template = new org.eclipse.birt.core.template.TemplateParser( )
.parse( text );
templateRef = new SoftReference( template );
templates.put( text, templateRef );
}
catch ( Exception ex )
{
ex.printStackTrace( );
}
return template;
}
String executeTemplate( TextTemplate template, HashMap values )
{
return new TemplateExecutor( context ).execute( template, values );
}
public Object visitList( IListContent list, Object value)
{
if ( list.getGenerateBy( ) instanceof ListItemDesign )
{
handleOnRender( list );
}
return list;
}
public Object visitTable( ITableContent table, Object value )
{
handleOnRender( table );
String captionText = table.getCaption( );
String captionKey = table.getCaptionKey( );
captionText = localize( table, captionKey, captionText );
table.setCaption( captionText );
return table;
}
public Object visitRow( IRowContent row, Object value )
{
handleOnRender( row );
return row;
}
public Object visitCell( ICellContent cell, Object value )
{
handleOnRender( cell );
return cell;
}
/**
* handle the data content.
*
* @param data
* data content object
*/
public Object visitData( IDataContent data, Object value )
{
handleOnRender( data );
processData( data );
return data;
}
/**
* process the data content
*
* <li> localize the help text
* <li> format the value
* <li> handle it as it is an text.
*
* @param data
* data object
*/
protected void processData( IDataContent data )
{
String helpText = localize( data, data.getHelpKey( ), data.getHelpText( ) );
data.setHelpText( helpText );
String text = ""; //$NON-NLS-1$
if ( data.getLabelKey( ) != null || data.getLabelText( ) != null )
{
text = localize( data, data.getLabelKey( ), data.getLabelText( ) );
}
else
{
Object value = data.getValue( );
if ( value != null )
{
IStyle style = data.getComputedStyle( );
if ( value instanceof Number )
{
String format = style.getNumberFormat( );
NumberFormatter fmt = context.getNumberFormatter( format );
text = fmt.format( (Number) value );
CSSValue align = style
.getProperty( IStyle.STYLE_NUMBER_ALIGN );
if ( align != null && align != CSSValueConstants.NONE_VALUE )
{
data.getStyle( ).setProperty( IStyle.STYLE_TEXT_ALIGN,
align );
}
}
else if ( value instanceof String )
{
StringFormatter fmt = context.getStringFormatter( style
.getStringFormat( ) );
text = fmt.format( (String) value );
}
else if ( value instanceof Date )
{
DateFormatter fmt = context.getDateFormatter( style
.getDateFormat( ) );
text = fmt.format( (Date) value );
}
else
{
text = value.toString( );
}
}
}
//text can be null value after applying format
if(text!=null)
{
data.setText( text );
}
else
{
data.setText( "" ); //$NON-NLS-1$
}
}
/**
* handle the label.
*
* @param label
* label content
*/
public Object visitLabel( ILabelContent label, Object value )
{
handleOnRender( label );
processLabel( label );
return label;
}
/**
* process the label content
*
* <li> localize the help text
* <li> localize the label content
* <li> handle it as it is an text
*
* @param label
* label object
*/
protected void processLabel( ILabelContent label )
{
String helpText = localize( label, label.getHelpKey( ), label.getHelpText( ) );
label.setHelpText( helpText );
if ( label.getText( ) == null )
{
String text = localize( label, label.getLabelKey( ), label.getLabelText( ) );
label.setText( text );
}
}
public Object visitText( ITextContent text, Object value )
{
handleOnRender( text );
return value;
}
public Object visitForeign( IForeignContent foreignContent, Object value )
{
IReportContent reportContent = getReportContent( );
String rawFormat = foreignContent.getRawType( );
Object rawValue = foreignContent.getRawValue( );
if ( IForeignContent.TEMPLATE_TYPE.equals( rawFormat ) )
{
handleOnRender( foreignContent );
processTemplateContent( foreignContent );
return foreignContent;
}
if ( IForeignContent.EXTERNAL_TYPE.equals( rawFormat ) )
{
return processExtendedContent( foreignContent );
}
if ( IForeignContent.IMAGE_TYPE.equals( rawFormat ) )
{
if ( rawValue instanceof IImageContent )
{
IImageContent image = (IImageContent) rawValue;
processImage( image );
return image;
}
if ( rawValue instanceof byte[] )
{
IImageContent imageContent = reportContent
.createImageContent( foreignContent );
imageContent.setImageSource( IImageContent.IMAGE_EXPRESSION );
imageContent.setData( (byte[]) rawValue );
processImage( imageContent );
return imageContent;
}
}
if ( IForeignContent.TEXT_TYPE.equals( rawFormat ) )
{
handleOnRender( foreignContent );
ITextContent textContent = reportContent
.createDataContent( foreignContent );
textContent.setText( rawValue == null ? "" : rawValue.toString( ) ); //$NON-NLS-1$
return textContent;
}
if ( IForeignContent.HTML_TYPE.equals( rawFormat ) )
{
handleOnRender( foreignContent );
String key = foreignContent.getRawKey( );
if (key != null)
{
String text = localize( foreignContent, key, null);
if (text != null)
{
foreignContent.setRawValue( text );
}
}
return foreignContent;
}
if ( IForeignContent.VALUE_TYPE.equals( rawFormat ) )
{
handleOnRender( foreignContent );
IDataContent dataContent = reportContent
.createDataContent( foreignContent );
dataContent.setValue( rawValue );
processData( dataContent );
return dataContent;
}
return foreignContent;
}
/**
* localzie the text.
*
* @param key
* text key
* @param text
* default text
* @return localized text.
*/
private String localize( IContent content, String key, String text )
{
assert ( content != null );
if ( content.getGenerateBy( ) != null )
{
DesignElementHandle element = ( (ReportItemDesign) content
.getGenerateBy( ) ).getHandle( );
if ( key != null && element != null )
{
String t = ModuleUtil.getExternalizedValue( element, key, text,
ULocale.forLocale( locale ) );
if ( t != null )
{
return t;
}
}
}
return text;
}
public Object visitImage( IImageContent image, Object value )
{
handleOnRender( image );
processImage( image );
return image;
}
protected void processImage( IImageContent image )
{
String altText = localize( image, image.getAltTextKey( ), image.getAltText( ) );
image.setAltText( altText );
String helpText = localize( image, image.getHelpKey( ), image.getHelpText( ) );
image.setHelpText( helpText );
}
/**
* handle the template result.
*
* @param foreignContent
*/
protected void processTemplateContent( IForeignContent foreignContent )
{
assert IForeignContent.TEMPLATE_TYPE.equals( foreignContent
.getRawType( ) );
if ( foreignContent.getGenerateBy( ) instanceof TextItemDesign )
{
TextItemDesign design = (TextItemDesign) foreignContent
.getGenerateBy( );
String text = null;
HashMap rawValues = null;
if ( foreignContent.getRawValue( ) instanceof Object[] )
{
Object[] rawValue = (Object[]) foreignContent.getRawValue( );
assert rawValue.length == 2;
assert rawValue[0] == null || rawValue[0] instanceof String;
if ( rawValue[0] != null )
{
text = (String )rawValue[0];
}
if ( rawValue[1] instanceof HashMap )
{
rawValues = (HashMap)rawValue[1];
}
}
if ( text == null )
{
text = localize( foreignContent, design.getTextKey( ), design.getText( ) );
}
TextTemplate template = parseTemplate( text );
String result = executeTemplate( template, rawValues );
foreignContent.setRawType( IForeignContent.HTML_TYPE );
foreignContent.setRawValue( result );
}
}
protected String getOutputFormat()
{
return outputFormat;
}
/**
* @return whether the output format is for printing
*/
protected boolean isForPrinting( )
{
String outputFormat = getOutputFormat( );
if ( "FO".equalsIgnoreCase( outputFormat )
|| "PDF".equalsIgnoreCase( outputFormat )
||"POSTSCRIPT".equalsIgnoreCase( outputFormat ))
return true;
return false;
}
/**
* handle an extended item.
*
* @param content
* the object.
*/
protected IContent processExtendedContent( IForeignContent content )
{
assert IForeignContent.EXTERNAL_TYPE.equals( content.getRawType( ) );
assert content.getGenerateBy( ) instanceof ExtendedItemDesign;
IContent generatedContent = content;
ExtendedItemDesign design = (ExtendedItemDesign) content
.getGenerateBy( );
ExtendedItemHandle handle = (ExtendedItemHandle) design.getHandle( );
String tagName = handle.getExtensionName( );
if ( "Chart".equals( tagName ) )
{
IHTMLImageHandler imageHandler = context.getImageHandler( );
if ( imageHandler != null )
{
String imageId = content.getInstanceID( ).toString( );
CachedImage cachedImage = imageHandler.getCachedImage( imageId,
IImage.CUSTOM_IMAGE, context.getReportContext( ) );
if ( cachedImage != null )
{
IImageContent imageObj = getReportContent( )
.createImageContent( content );
imageObj.setParent( content.getParent( ) );
// Set image map
imageObj.setImageSource( IImageContent.IMAGE_FILE );
imageObj.setURI( cachedImage.getURL( ) );
imageObj.setMIMEType( cachedImage.getMIMEType( ) );
imageObj.setImageMap( cachedImage.getImageMap( ) );
imageObj.setAltText( content.getAltText( ) );
imageObj.setAltTextKey( content.getAltTextKey( ) );
processImage( imageObj );
return imageObj;
}
}
}
// call the presentation peer to create the content object
IReportItemPresentation itemPresentation = ExtensionManager
.getInstance( ).createPresentationItem( tagName );
if ( itemPresentation != null )
{
itemPresentation.setModelObject( handle );
itemPresentation.setApplicationClassLoader( context
.getApplicationClassLoader( ) );
itemPresentation.setScriptContext( context.getReportContext( ) );
IBaseQueryDefinition[] queries = (IBaseQueryDefinition[])design.getQueries( );
itemPresentation.setReportQueries( queries );
itemPresentation.setDynamicStyle( content.getComputedStyle( ) );
Map appContext = context.getAppContext( );
int resolution = 0;
if ( appContext != null )
{
Object tmp = appContext.get( EngineConstants.APPCONTEXT_CHART_RESOLUTION );
if ( tmp != null && tmp instanceof Number )
{
resolution = ( (Number) tmp ).intValue( );
if ( resolution < 96 )
{
resolution = 96;
}
}
}
if ( 0 == resolution )
{
if ( isForPrinting( ) )
{
resolution = 192;
}
else
{
resolution = 96;
}
}
itemPresentation.setResolution( resolution );
itemPresentation.setLocale( locale );
String supportedImageFormats = "PNG;GIF;JPG;BMP;"; //$NON-NLS-1$
IRenderOption renderOption = context.getRenderOption( );
String formats = renderOption.getSupportedImageFormats( );
if ( formats != null )
{
supportedImageFormats = formats;
}
itemPresentation.setSupportedImageFormats( supportedImageFormats ); // Default
itemPresentation.setActionHandler( context.getActionHandler( ) );
// value
String outputFormat = getOutputFormat( );
itemPresentation.setOutputFormat( outputFormat );
Object rawValue = content.getRawValue( );
if ( rawValue instanceof byte[] )
{
byte[] values = (byte[]) rawValue;
itemPresentation
.deserialize( new ByteArrayInputStream( values ) );
}
IRowSet[] rowSets = null;
IBaseResultSet[] rsets = context.getResultSets();
if ( queries == null )
{
DesignElementHandle elementHandle = design.getHandle( );
if ( elementHandle instanceof ReportElementHandle )
{
queries = (IBaseQueryDefinition[]) context.getRunnable( )
.getReportIR( ).getQueryByReportHandle(
(ReportElementHandle) elementHandle );
}
}
if ( queries != null )
{
if ( rsets != null )
{
rowSets = new IRowSet[rsets.length];
for ( int i = 0; i < rowSets.length; i++ )
{
rowSets[i] = new RowSet( context,
(IQueryResultSet) rsets[i] );
}
}
}
else
{
if ( rsets != null )
{
rowSets = new IRowSet[1];
rowSets[0] = new SingleRowSet( context,
(IQueryResultSet) rsets[0] );
}
}
try
{
Object output = itemPresentation.onRowSets( rowSets );
if ( output != null )
{
int type = itemPresentation.getOutputType( );
String imageMIMEType = itemPresentation.getImageMIMEType( );
generatedContent = processExtendedContent( content, type, output, imageMIMEType );
}
itemPresentation.finish( );
}
catch ( BirtException ex )
{
context.addException( design.getHandle( ), ex );
logger.log( Level.SEVERE, ex.getMessage( ), ex );
}
}
return generatedContent;
}
protected IContent processExtendedContent( IForeignContent content, int type,
Object output, String imageMIMEType )
{
assert IForeignContent.EXTERNAL_TYPE.equals( content.getRawType( ) );
assert output != null;
IReportContent reportContent = getReportContent( );
switch ( type )
{
case IReportItemPresentation.OUTPUT_NONE :
break;
case IReportItemPresentation.OUTPUT_AS_IMAGE :
case IReportItemPresentation.OUTPUT_AS_IMAGE_WITH_MAP :
// the output object is a image, so create a image content
// object
Object imageMap = null;
byte[] imageContent = new byte[0];
Object image = output;
if ( type == IReportItemPresentation.OUTPUT_AS_IMAGE_WITH_MAP )
{
// OUTPUT_AS_IMAGE_WITH_MAP
Object[] imageWithMap = (Object[]) output;
if ( imageWithMap.length > 0 )
{
image = imageWithMap[0];
}
if ( imageWithMap.length > 1 )
{
imageMap = imageWithMap[1];
}
}
if ( image instanceof InputStream )
{
imageContent = readContent( (InputStream) image );
}
else if ( output instanceof byte[] )
{
imageContent = (byte[]) image;
}
else
{
assert false;
logger.log( Level.WARNING,
"unsupported image type:{0}", output ); //$NON-NLS-1$
}
IImageContent imageObj = reportContent.createImageContent( content );
imageObj.setParent( content.getParent( ) );
// Set image map
imageObj.setImageSource( IImageContent.IMAGE_EXPRESSION );
imageObj.setData( imageContent );
imageObj.setImageMap( imageMap );
imageObj.setMIMEType( imageMIMEType );
imageObj.setAltText( content.getAltText( ) );
imageObj.setAltTextKey( content.getAltTextKey( ) );
processImage( imageObj );
return imageObj;
case IReportItemPresentation.OUTPUT_AS_CUSTOM :
IDataContent dataObj = reportContent.createDataContent( content );
dataObj.setValue( output );
processData( dataObj );
return dataObj;
case IReportItemPresentation.OUTPUT_AS_HTML_TEXT :
content.setRawType( IForeignContent.HTML_TYPE );
content.setRawValue( output.toString( ) );
return content;
case IReportItemPresentation.OUTPUT_AS_TEXT :
ITextContent textObj = reportContent.createTextContent( );
textObj.setText( output.toString( ) );
return textObj;
default :
assert false;
logger.log( Level.WARNING, "unsupported output format:{0}", //$NON-NLS-1$
new Integer( type ) );
}
return content;
}
/**
* read the content of input stream.
*
* @param in
* input content
* @return content in the stream.
*/
static protected byte[] readContent( InputStream in )
{
BufferedInputStream bin = in instanceof BufferedInputStream
? (BufferedInputStream) in
: new BufferedInputStream( in );
ByteArrayOutputStream out = new ByteArrayOutputStream( 1024 );
byte[] buffer = new byte[1024];
int readSize = 0;
try
{
readSize = bin.read( buffer );
while ( readSize != -1 )
{
out.write( buffer, 0, readSize );
readSize = bin.read( buffer );
}
}
catch ( IOException ex )
{
logger.log( Level.SEVERE, ex.getMessage( ), ex );
}
return out.toByteArray( );
}
protected void handleOnRender( IContent content )
{
if ( content.getGenerateBy( ) != null )
{
onRenderVisitor.onRender( content );
}
}
}
|
package org.cyclops.integrateddynamics.part.aspect.write;
import com.google.common.base.Optional;
import com.google.common.base.Predicate;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import net.minecraft.block.state.IBlockState;
import net.minecraft.init.SoundEvents;
import net.minecraft.item.ItemStack;
import net.minecraft.util.SoundCategory;
import net.minecraft.util.SoundEvent;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.World;
import net.minecraftforge.event.world.NoteBlockEvent;
import net.minecraftforge.fluids.FluidStack;
import org.apache.commons.lang3.tuple.Pair;
import org.apache.commons.lang3.tuple.Triple;
import org.cyclops.integrateddynamics.api.evaluate.EvaluationException;
import org.cyclops.integrateddynamics.api.evaluate.variable.IValue;
import org.cyclops.integrateddynamics.api.evaluate.variable.IValueType;
import org.cyclops.integrateddynamics.api.evaluate.variable.IVariable;
import org.cyclops.integrateddynamics.api.part.PartTarget;
import org.cyclops.integrateddynamics.api.part.aspect.property.IAspectProperties;
import org.cyclops.integrateddynamics.api.part.aspect.property.IAspectPropertyTypeInstance;
import org.cyclops.integrateddynamics.api.part.write.IPartStateWriter;
import org.cyclops.integrateddynamics.api.part.write.IPartTypeWriter;
import org.cyclops.integrateddynamics.core.evaluate.variable.*;
import org.cyclops.integrateddynamics.core.part.aspect.build.AspectBuilder;
import org.cyclops.integrateddynamics.core.part.aspect.build.IAspectValuePropagator;
import org.cyclops.integrateddynamics.core.part.aspect.build.IAspectWriteDeactivator;
import org.cyclops.integrateddynamics.core.part.aspect.property.AspectProperties;
import org.cyclops.integrateddynamics.core.part.aspect.property.AspectPropertyTypeInstance;
import org.cyclops.integrateddynamics.part.aspect.read.AspectReadBuilders;
import org.cyclops.integrateddynamics.part.aspect.write.redstone.IWriteRedstoneComponent;
import org.cyclops.integrateddynamics.part.aspect.write.redstone.WriteRedstoneComponent;
import java.util.List;
/**
* Collection of aspect write builders and value propagators.
* @author rubensworks
*/
public class AspectWriteBuilders {
public static final AspectBuilder<ValueTypeBoolean.ValueBoolean, ValueTypeBoolean, Triple<PartTarget, IAspectProperties, ValueTypeBoolean.ValueBoolean>>
BUILDER_BOOLEAN = getValue(AspectBuilder.forWriteType(ValueTypes.BOOLEAN));
public static final AspectBuilder<ValueTypeInteger.ValueInteger, ValueTypeInteger, Triple<PartTarget, IAspectProperties, ValueTypeInteger.ValueInteger>>
BUILDER_INTEGER = getValue(AspectBuilder.forWriteType(ValueTypes.INTEGER));
public static final AspectBuilder<ValueTypeDouble.ValueDouble, ValueTypeDouble, Triple<PartTarget, IAspectProperties, ValueTypeDouble.ValueDouble>>
BUILDER_DOUBLE = getValue(AspectBuilder.forWriteType(ValueTypes.DOUBLE));
public static final AspectBuilder<ValueTypeString.ValueString, ValueTypeString, Triple<PartTarget, IAspectProperties, ValueTypeString.ValueString>>
BUILDER_STRING = getValue(AspectBuilder.forWriteType(ValueTypes.STRING));
public static final AspectBuilder<ValueTypeList.ValueList, ValueTypeList, Triple<PartTarget, IAspectProperties, ValueTypeList.ValueList>>
BUILDER_LIST = getValue(AspectBuilder.forWriteType(ValueTypes.LIST));
public static final AspectBuilder<ValueObjectTypeItemStack.ValueItemStack, ValueObjectTypeItemStack, Triple<PartTarget, IAspectProperties, ValueObjectTypeItemStack.ValueItemStack>>
BUILDER_ITEMSTACK = getValue(AspectBuilder.forWriteType(ValueTypes.OBJECT_ITEMSTACK));
public static final AspectBuilder<ValueObjectTypeFluidStack.ValueFluidStack, ValueObjectTypeFluidStack, Triple<PartTarget, IAspectProperties, ValueObjectTypeFluidStack.ValueFluidStack>>
BUILDER_FLUIDSTACK = getValue(AspectBuilder.forWriteType(ValueTypes.OBJECT_FLUIDSTACK));
public static final AspectBuilder<ValueTypeOperator.ValueOperator, ValueTypeOperator, Triple<PartTarget, IAspectProperties, ValueTypeOperator.ValueOperator>>
BUILDER_OPERATOR = getValue(AspectBuilder.forWriteType(ValueTypes.OPERATOR));
public static final IAspectValuePropagator<Triple<PartTarget, IAspectProperties, ValueTypeBoolean.ValueBoolean>, Triple<PartTarget, IAspectProperties, Boolean>> PROP_GET_BOOLEAN = new IAspectValuePropagator<Triple<PartTarget, IAspectProperties, ValueTypeBoolean.ValueBoolean>, Triple<PartTarget, IAspectProperties, Boolean>>() {
@Override
public Triple<PartTarget, IAspectProperties, Boolean> getOutput(Triple<PartTarget, IAspectProperties, ValueTypeBoolean.ValueBoolean> input) throws EvaluationException {
return Triple.of(input.getLeft(), input.getMiddle(), input.getRight().getRawValue());
}
};
public static final IAspectValuePropagator<Triple<PartTarget, IAspectProperties,ValueTypeInteger.ValueInteger>, Triple<PartTarget, IAspectProperties, Integer>> PROP_GET_INTEGER = new IAspectValuePropagator<Triple<PartTarget, IAspectProperties, ValueTypeInteger.ValueInteger>, Triple<PartTarget, IAspectProperties, Integer>>() {
@Override
public Triple<PartTarget, IAspectProperties, Integer> getOutput(Triple<PartTarget, IAspectProperties, ValueTypeInteger.ValueInteger> input) throws EvaluationException {
return Triple.of(input.getLeft(), input.getMiddle(), input.getRight().getRawValue());
}
};
public static final IAspectValuePropagator<Triple<PartTarget, IAspectProperties, ValueTypeDouble.ValueDouble>, Triple<PartTarget, IAspectProperties, Double>> PROP_GET_DOUBLE = new IAspectValuePropagator<Triple<PartTarget, IAspectProperties, ValueTypeDouble.ValueDouble>, Triple<PartTarget, IAspectProperties, Double>>() {
@Override
public Triple<PartTarget, IAspectProperties, Double> getOutput(Triple<PartTarget, IAspectProperties, ValueTypeDouble.ValueDouble> input) throws EvaluationException {
return Triple.of(input.getLeft(), input.getMiddle(), input.getRight().getRawValue());
}
};
public static final IAspectValuePropagator<Triple<PartTarget, IAspectProperties, ValueTypeLong.ValueLong>, Triple<PartTarget, IAspectProperties, Long>> PROP_GET_LONG = new IAspectValuePropagator<Triple<PartTarget, IAspectProperties, ValueTypeLong.ValueLong>, Triple<PartTarget, IAspectProperties, Long>>() {
@Override
public Triple<PartTarget, IAspectProperties, Long> getOutput(Triple<PartTarget, IAspectProperties, ValueTypeLong.ValueLong> input) throws EvaluationException {
return Triple.of(input.getLeft(), input.getMiddle(), input.getRight().getRawValue());
}
};
public static final IAspectValuePropagator<Triple<PartTarget, IAspectProperties, ValueObjectTypeItemStack.ValueItemStack>, Triple<PartTarget, IAspectProperties, ItemStack>> PROP_GET_ITEMSTACK = new IAspectValuePropagator<Triple<PartTarget, IAspectProperties, ValueObjectTypeItemStack.ValueItemStack>, Triple<PartTarget, IAspectProperties, ItemStack>>() {
@Override
public Triple<PartTarget, IAspectProperties, ItemStack> getOutput(Triple<PartTarget, IAspectProperties, ValueObjectTypeItemStack.ValueItemStack> input) throws EvaluationException {
ItemStack optional = input.getRight().getRawValue();
return Triple.of(input.getLeft(), input.getMiddle(), !optional.isEmpty() ? optional : null);
}
};
public static final IAspectValuePropagator<Triple<PartTarget, IAspectProperties, ValueTypeString.ValueString>, Triple<PartTarget, IAspectProperties, String>> PROP_GET_STRING = new IAspectValuePropagator<Triple<PartTarget, IAspectProperties, ValueTypeString.ValueString>, Triple<PartTarget, IAspectProperties, String>>() {
@Override
public Triple<PartTarget, IAspectProperties, String> getOutput(Triple<PartTarget, IAspectProperties, ValueTypeString.ValueString> input) throws EvaluationException {
return Triple.of(input.getLeft(), input.getMiddle(), input.getRight().getRawValue());
}
};
public static final IAspectValuePropagator<Triple<PartTarget, IAspectProperties, ValueObjectTypeBlock.ValueBlock>, Triple<PartTarget, IAspectProperties, IBlockState>> PROP_GET_BLOCK = new IAspectValuePropagator<Triple<PartTarget, IAspectProperties, ValueObjectTypeBlock.ValueBlock>, Triple<PartTarget, IAspectProperties, IBlockState>>() {
@Override
public Triple<PartTarget, IAspectProperties, IBlockState> getOutput(Triple<PartTarget, IAspectProperties, ValueObjectTypeBlock.ValueBlock> input) throws EvaluationException {
Optional<IBlockState> optional = input.getRight().getRawValue();
return Triple.of(input.getLeft(), input.getMiddle(), optional.isPresent() ? optional.get() : null);
}
};
public static final IAspectValuePropagator<Triple<PartTarget, IAspectProperties, ValueObjectTypeFluidStack.ValueFluidStack>, Triple<PartTarget, IAspectProperties, FluidStack>> PROP_GET_FLUIDSTACK = new IAspectValuePropagator<Triple<PartTarget, IAspectProperties, ValueObjectTypeFluidStack.ValueFluidStack>, Triple<PartTarget, IAspectProperties, FluidStack>>() {
@Override
public Triple<PartTarget, IAspectProperties, FluidStack> getOutput(Triple<PartTarget, IAspectProperties, ValueObjectTypeFluidStack.ValueFluidStack> input) throws EvaluationException {
Optional<FluidStack> optional = input.getRight().getRawValue();
return Triple.of(input.getLeft(), input.getMiddle(), optional.isPresent() ? optional.get() : null);
}
};
public static final class Audio {
public static final IAspectPropertyTypeInstance<ValueTypeDouble, ValueTypeDouble.ValueDouble> PROP_VOLUME =
new AspectPropertyTypeInstance<>(ValueTypes.DOUBLE, "aspect.aspecttypes.integrateddynamics.double.volume.name", AspectReadBuilders.VALIDATOR_DOUBLE_POSITIVE);
public static final IAspectPropertyTypeInstance<ValueTypeDouble, ValueTypeDouble.ValueDouble> PROP_FREQUENCY =
new AspectPropertyTypeInstance<>(ValueTypes.DOUBLE, "aspect.aspecttypes.integrateddynamics.double.frequency.name", AspectReadBuilders.VALIDATOR_DOUBLE_POSITIVE);
public static final IAspectProperties PROPERTIES_NOTE = new AspectProperties(Sets.<IAspectPropertyTypeInstance>newHashSet(
PROP_VOLUME
));
public static final IAspectProperties PROPERTIES_SOUND = new AspectProperties(ImmutableList.<IAspectPropertyTypeInstance>of(
PROP_VOLUME,
PROP_FREQUENCY
));
static {
Predicate<ValueTypeDouble.ValueDouble> POSITIVE = new Predicate<ValueTypeDouble.ValueDouble>() {
@Override
public boolean apply(ValueTypeDouble.ValueDouble input) {
return input.getRawValue() >= 0;
}
};
PROPERTIES_NOTE.setValue(PROP_VOLUME, ValueTypeDouble.ValueDouble.of(3D));
PROPERTIES_SOUND.setValue(PROP_VOLUME, ValueTypeDouble.ValueDouble.of(3D));
PROPERTIES_SOUND.setValue(PROP_FREQUENCY, ValueTypeDouble.ValueDouble.of(1D));
}
private static final List<SoundEvent> INSTRUMENTS = Lists.newArrayList(new SoundEvent[] {SoundEvents.BLOCK_NOTE_HARP, SoundEvents.BLOCK_NOTE_BASEDRUM, SoundEvents.BLOCK_NOTE_SNARE, SoundEvents.BLOCK_NOTE_HAT, SoundEvents.BLOCK_NOTE_BASS});
private static SoundEvent getInstrument(int id) {
if (id < 0 || id >= INSTRUMENTS.size()) {
id = 0;
}
return INSTRUMENTS.get(id);
}
public static final IAspectValuePropagator<Triple<PartTarget, IAspectProperties, Pair<NoteBlockEvent.Instrument, Integer>>, Void> PROP_SET = new IAspectValuePropagator<Triple<PartTarget, IAspectProperties, Pair<NoteBlockEvent.Instrument, Integer>>, Void>() {
@Override
public Void getOutput(Triple<PartTarget, IAspectProperties, Pair<NoteBlockEvent.Instrument, Integer>> input) {
IAspectProperties properties = input.getMiddle();
BlockPos pos = input.getLeft().getTarget().getPos().getBlockPos();
int eventID = input.getRight().getLeft().ordinal();
int eventParam = input.getRight().getRight();
if(eventParam >= 0 && eventParam <= 24) {
World world = input.getLeft().getTarget().getPos().getWorld();
NoteBlockEvent.Play e = new NoteBlockEvent.Play(world, pos, world.getBlockState(pos), eventParam, eventID);
if (!net.minecraftforge.common.MinecraftForge.EVENT_BUS.post(e)) {
float f = (float) Math.pow(2.0D, (double) (eventParam - 12) / 12.0D);
float volume = (float) properties.getValue(PROP_VOLUME).getRawValue();
world.playSound(null,
(double) pos.getX() + 0.5D, (double) pos.getY() + 0.5D, (double) pos.getZ() + 0.5D,
getInstrument(eventID), SoundCategory.RECORDS, volume, f);
}
}
return null;
}
};
public static IAspectValuePropagator<Triple<PartTarget, IAspectProperties, Integer>, Triple<PartTarget, IAspectProperties, Pair<NoteBlockEvent.Instrument, Integer>>>
propWithInstrument(final NoteBlockEvent.Instrument instrument) {
return new IAspectValuePropagator<Triple<PartTarget, IAspectProperties, Integer>, Triple<PartTarget, IAspectProperties, Pair<NoteBlockEvent.Instrument, Integer>>>() {
@Override
public Triple<PartTarget, IAspectProperties, Pair<NoteBlockEvent.Instrument, Integer>> getOutput(Triple<PartTarget, IAspectProperties, Integer> input) throws EvaluationException {
return Triple.of(input.getLeft(), input.getMiddle(), Pair.of(instrument, input.getRight()));
}
};
}
public static final AspectBuilder<ValueTypeInteger.ValueInteger, ValueTypeInteger, Triple<PartTarget, IAspectProperties, Integer>>
BUILDER_INTEGER = AspectWriteBuilders.BUILDER_INTEGER.appendKind("audio").handle(PROP_GET_INTEGER);
public static final AspectBuilder<ValueTypeInteger.ValueInteger, ValueTypeInteger, Triple<PartTarget, IAspectProperties, Integer>>
BUILDER_INTEGER_INSTRUMENT = BUILDER_INTEGER.appendKind("instrument").withProperties(PROPERTIES_NOTE);
public static final AspectBuilder<ValueTypeString.ValueString, ValueTypeString, Triple<PartTarget, IAspectProperties, String>>
BUILDER_STRING = AspectWriteBuilders.BUILDER_STRING.appendKind("audio").handle(PROP_GET_STRING);
}
public static final class Effect {
public static final IAspectPropertyTypeInstance<ValueTypeDouble, ValueTypeDouble.ValueDouble> PROP_OFFSET_X =
new AspectPropertyTypeInstance<>(ValueTypes.DOUBLE, "aspect.aspecttypes.integrateddynamics.double.offset_x.name", AspectReadBuilders.VALIDATOR_DOUBLE_POSITIVE);
public static final IAspectPropertyTypeInstance<ValueTypeDouble, ValueTypeDouble.ValueDouble> PROP_OFFSET_Y =
new AspectPropertyTypeInstance<>(ValueTypes.DOUBLE, "aspect.aspecttypes.integrateddynamics.double.offset_y.name", AspectReadBuilders.VALIDATOR_DOUBLE_POSITIVE);
public static final IAspectPropertyTypeInstance<ValueTypeDouble, ValueTypeDouble.ValueDouble> PROP_OFFSET_Z =
new AspectPropertyTypeInstance<>(ValueTypes.DOUBLE, "aspect.aspecttypes.integrateddynamics.double.offset_z.name", AspectReadBuilders.VALIDATOR_DOUBLE_POSITIVE);
public static final IAspectPropertyTypeInstance<ValueTypeInteger, ValueTypeInteger.ValueInteger> PROP_PARTICLES =
new AspectPropertyTypeInstance<>(ValueTypes.INTEGER, "aspect.aspecttypes.integrateddynamics.integer.particles.name", AspectReadBuilders.VALIDATOR_INTEGER_POSITIVE);
public static final IAspectPropertyTypeInstance<ValueTypeDouble, ValueTypeDouble.ValueDouble> PROP_SPREAD_X =
new AspectPropertyTypeInstance<>(ValueTypes.DOUBLE, "aspect.aspecttypes.integrateddynamics.double.spread_x.name", AspectReadBuilders.VALIDATOR_DOUBLE_POSITIVE);
public static final IAspectPropertyTypeInstance<ValueTypeDouble, ValueTypeDouble.ValueDouble> PROP_SPREAD_Y =
new AspectPropertyTypeInstance<>(ValueTypes.DOUBLE, "aspect.aspecttypes.integrateddynamics.double.spread_y.name", AspectReadBuilders.VALIDATOR_DOUBLE_POSITIVE);
public static final IAspectPropertyTypeInstance<ValueTypeDouble, ValueTypeDouble.ValueDouble> PROP_SPREAD_Z =
new AspectPropertyTypeInstance<>(ValueTypes.DOUBLE, "aspect.aspecttypes.integrateddynamics.double.spread_z.name", AspectReadBuilders.VALIDATOR_DOUBLE_POSITIVE);
public static final IAspectPropertyTypeInstance<ValueTypeBoolean, ValueTypeBoolean.ValueBoolean> PROP_FORCE =
new AspectPropertyTypeInstance<>(ValueTypes.BOOLEAN, "aspect.aspecttypes.integrateddynamics.boolean.force_particle.name");
public static final IAspectProperties PROPERTIES_PARTICLE = new AspectProperties(ImmutableList.<IAspectPropertyTypeInstance>of(
PROP_OFFSET_X,
PROP_OFFSET_Y,
PROP_OFFSET_Z,
PROP_PARTICLES,
PROP_SPREAD_X,
PROP_SPREAD_Y,
PROP_SPREAD_Z,
PROP_FORCE
));
static {
PROPERTIES_PARTICLE.setValue(PROP_OFFSET_X, ValueTypeDouble.ValueDouble.of(0.5D));
PROPERTIES_PARTICLE.setValue(PROP_OFFSET_Z, ValueTypeDouble.ValueDouble.of(0.5D));
PROPERTIES_PARTICLE.setValue(PROP_OFFSET_Y, ValueTypeDouble.ValueDouble.of(0.5D));
PROPERTIES_PARTICLE.setValue(PROP_PARTICLES, ValueTypeInteger.ValueInteger.of(1));
PROPERTIES_PARTICLE.setValue(PROP_SPREAD_X, ValueTypeDouble.ValueDouble.of(0.0D));
PROPERTIES_PARTICLE.setValue(PROP_SPREAD_Y, ValueTypeDouble.ValueDouble.of(0.0D));
PROPERTIES_PARTICLE.setValue(PROP_SPREAD_Z, ValueTypeDouble.ValueDouble.of(0.0D));
PROPERTIES_PARTICLE.setValue(PROP_FORCE, ValueTypeBoolean.ValueBoolean.of(false));
}
public static final AspectBuilder<ValueTypeDouble.ValueDouble, ValueTypeDouble, Triple<PartTarget, IAspectProperties, Double>>
BUILDER_DOUBLE = AspectWriteBuilders.BUILDER_DOUBLE.appendKind("effect").handle(PROP_GET_DOUBLE);
public static final AspectBuilder<ValueTypeDouble.ValueDouble, ValueTypeDouble, Triple<PartTarget, IAspectProperties, Double>>
BUILDER_DOUBLE_PARTICLE = BUILDER_DOUBLE.withProperties(PROPERTIES_PARTICLE);
}
public static final class Redstone {
private static final IWriteRedstoneComponent WRITE_REDSTONE_COMPONENT = new WriteRedstoneComponent();
public static final IAspectValuePropagator<Triple<PartTarget, IAspectProperties, Integer>, Void> PROP_SET = new IAspectValuePropagator<Triple<PartTarget, IAspectProperties, Integer>, Void>() {
@Override
public Void getOutput(Triple<PartTarget, IAspectProperties, Integer> input) {
boolean strongPower = input.getMiddle().getValue(PROP_STRONG_POWER).getRawValue();
WRITE_REDSTONE_COMPONENT.setRedstoneLevel(input.getLeft(), input.getRight(), strongPower);
return null;
}
};
public static final IAspectWriteDeactivator DEACTIVATOR = new IAspectWriteDeactivator() {
@Override
public <P extends IPartTypeWriter<P, S>, S extends IPartStateWriter<P>> void onDeactivate(P partType, PartTarget target, S state) {
WRITE_REDSTONE_COMPONENT.deactivate(target);
}
};
public static final IAspectPropertyTypeInstance<ValueTypeBoolean, ValueTypeBoolean.ValueBoolean> PROP_STRONG_POWER =
new AspectPropertyTypeInstance<>(ValueTypes.BOOLEAN, "aspect.aspecttypes.integrateddynamics.boolean.strong_power.name");
public static final IAspectProperties PROPERTIES_REDSTONE = new AspectProperties(ImmutableList.<IAspectPropertyTypeInstance>of(
PROP_STRONG_POWER
));
static {
PROPERTIES_REDSTONE.setValue(PROP_STRONG_POWER, ValueTypeBoolean.ValueBoolean.of(false));
}
public static final AspectBuilder<ValueTypeBoolean.ValueBoolean, ValueTypeBoolean, Triple<PartTarget, IAspectProperties, Boolean>>
BUILDER_BOOLEAN = AspectWriteBuilders.BUILDER_BOOLEAN.appendKind("redstone").handle(PROP_GET_BOOLEAN).appendDeactivator(DEACTIVATOR).withProperties(PROPERTIES_REDSTONE);
public static final AspectBuilder<ValueTypeInteger.ValueInteger, ValueTypeInteger, Triple<PartTarget, IAspectProperties, Integer>>
BUILDER_INTEGER = AspectWriteBuilders.BUILDER_INTEGER.appendKind("redstone").handle(PROP_GET_INTEGER).appendDeactivator(DEACTIVATOR).withProperties(PROPERTIES_REDSTONE);
}
public static <V extends IValue, T extends IValueType<V>> AspectBuilder<V, T, Triple<PartTarget, IAspectProperties, V>> getValue(AspectBuilder<V, T, Triple<PartTarget, IAspectProperties, IVariable<V>>> builder) {
return builder.handle(new IAspectValuePropagator<Triple<PartTarget, IAspectProperties, IVariable<V>>, Triple<PartTarget, IAspectProperties, V>>() {
@Override
public Triple<PartTarget, IAspectProperties, V> getOutput(Triple<PartTarget, IAspectProperties, IVariable<V>> input) throws EvaluationException {
return Triple.of(input.getLeft(), input.getMiddle(), input.getRight().getValue());
}
});
}
}
|
package org.wikipathways.wp2rdf;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.Collections;
import org.bridgedb.DataSource;
import org.bridgedb.IDMapperException;
import org.bridgedb.IDMapperStack;
import org.bridgedb.bio.DataSourceTxt;
import org.junit.Assert;
import org.junit.Test;
import org.pathvisio.core.model.ConverterException;
import org.pathvisio.core.model.Pathway;
import org.wikipathways.wp2rdf.io.PathwayReader;
public abstract class AbstractWPConvertorTest extends AbstractConvertorTest {
public static void loadModelAsWPRDF(String gpmlFile, String wpid, String revision) throws ConverterException, FileNotFoundException, ClassNotFoundException, IOException, IDMapperException {
DataSourceTxt.init();
// the next line is needed until BridgeDb gets updated
DataSource.register("Cpx", "Complex Portal")
.identifiersOrgBase("http://identifiers.org/complexportal/")
.asDataSource();
DataSource.register("Pbd", "Digital Object Identifier").asDataSource();
DataSource.register("Pbm", "PubMed").asDataSource();
DataSource.register("Gpl", "Guide to Pharmacology Targets").asDataSource();
InputStream input = AbstractConvertorTest.class.getClassLoader().getResourceAsStream(gpmlFile);
Pathway pathway = PathwayReader.readPathway(input);
Assert.assertNotNull(pathway);
IDMapperStack stack = WPREST2RDF.maps();
model = GpmlConverter.convertWp(pathway, wpid, revision, stack, Collections.<String>emptyList());
Assert.assertNotNull(model);
// String ttlContent = toString(model);
// if (ttlContent.length() > 1000) ttlContent.substring(0,1000);
// System.out.println(ttlContent);
}
@Test
public void untypedPubMedRef() throws Exception {
String sparql = ResourceHelper.resourceAsString("structure/untypedPubMedRefs.rq");
StringMatrix table = SPARQLHelper.sparql(model, sparql);
Assert.assertNotNull(table);
Assert.assertEquals("No tping as wp:PublicationReference for PubMed URIs:\n" + table, 0, table.getRowCount());
}
}
|
package org.jivesoftware.smackx;
import java.util.*;
import org.jivesoftware.smack.packet.*;
import org.jivesoftware.smackx.packet.DataForm;
/**
* Represents a Form for gathering data. The form could be of the following types:
* <ul>
* <li>form -> Indicates a form to fill out.</li>
* <li>submit -> The form is filled out, and this is the data that is being returned from
* the form.</li>
* <li>cancel -> The form was cancelled. Tell the asker that piece of information.</li>
* <li>result -> Data results being returned from a search, or some other query.</li>
* </ul>
*
* Depending of the form's type different operations are available. For example, it's only possible
* to set answers if the form is of type "submit".
*
* @author Gaston Dombiak
*/
public class Form {
public static final String TYPE_FORM = "form";
public static final String TYPE_SUBMIT = "submit";
public static final String TYPE_CANCEL = "cancel";
public static final String TYPE_RESULT = "result";
private DataForm dataForm;
/**
* Returns a new ReportedData if the packet is used for gathering data and includes an
* extension that matches the elementName and namespace "x","jabber:x:data".
*
* @param packet the packet used for gathering data.
*/
public static Form getFormFrom(Packet packet) {
// Check if the packet includes the DataForm extension
PacketExtension packetExtension = packet.getExtension("x","jabber:x:data");
if (packetExtension != null) {
// Check if the existing DataForm is not a result of a search
DataForm dataForm = (DataForm) packetExtension;
if (dataForm.getReportedData() == null)
return new Form(dataForm);
}
// Otherwise return null
return null;
}
/**
* Creates a new Form that will wrap an existing DataForm. The wrapped DataForm must be
* used for gathering data.
*
* @param dataForm the data form used for gathering data.
*/
private Form(DataForm dataForm) {
this.dataForm = dataForm;
}
/**
* Creates a new Form of a given type from scratch.<p>
*
* Possible form types are:
* <ul>
* <li>form -> Indicates a form to fill out.</li>
* <li>submit -> The form is filled out, and this is the data that is being returned from
* the form.</li>
* <li>cancel -> The form was cancelled. Tell the asker that piece of information.</li>
* <li>result -> Data results being returned from a search, or some other query.</li>
* </ul>
*
* @param type the form's type (e.g. form, submit,cancel,result).
*/
public Form(String type) {
this.dataForm = new DataForm(type);
}
/**
* Adds a new field to complete as part of the form.
*
* @param field the field to complete.
*/
public void addField(FormField field) {
dataForm.addField(field);
}
public void setAnswer(String variable, String value) {
if (!isSubmitType()) {
throw new IllegalStateException("Cannot set an answer if the form is not of type " +
"\"submit\"");
}
FormField field = getField(variable);
if (field != null) {
field.resetValues();
field.addValue(value);
}
else {
throw new IllegalArgumentException("Couldn't find a field for the specified variable.");
}
}
public void setAnswer(String variable, List values) {
if (!isSubmitType()) {
throw new IllegalStateException("Cannot set an answer if the form is not of type " +
"\"submit\"");
}
FormField field = getField(variable);
if (field != null) {
field.resetValues();
field.addValues(values);
}
else {
throw new IllegalArgumentException("Couldn't find a field for the specified variable.");
}
}
/**
* Returns an Iterator for the fields that are part of the form.
*
* @return an Iterator for the fields that are part of the form.
*/
public Iterator getFields() {
return dataForm.getFields();
}
/**
* Returns the field of the form whose variable matches the specified variable.
* The fields of type FIXED will never be returned since they do not specify a
* variable.
*
* @param variable the variable to look for in the form fields.
* @return the field of the form whose variable matches the specified variable.
*/
public FormField getField(String variable) {
if (variable == null || variable.equals("")) {
throw new IllegalArgumentException("Variable must not be null or blank.");
}
// Look for the field whose variable matches the requested variable
FormField field;
for (Iterator it=getFields();it.hasNext();) {
field = (FormField)it.next();
if (variable.equals(field.getVariable())) {
return field;
}
}
return null;
}
/**
* Returns the instructions that explain how to fill out the form and what the form is about.
*
* @return instructions that explain how to fill out the form.
*/
public String getInstructions() {
return dataForm.getInstructions();
}
/**
* Returns the description of the data. It is similar to the title on a web page or an X
* window. You can put a <title/> on either a form to fill out, or a set of data results.
*
* @return description of the data.
*/
public String getTitle() {
return dataForm.getTitle();
}
/**
* Returns the meaning of the data within the context. The data could be part of a form
* to fill out, a form submission or data results.<p>
*
* Possible form types are:
* <ul>
* <li>form -> Indicates a form to fill out.</li>
* <li>submit -> The form is filled out, and this is the data that is being returned from
* the form.</li>
* <li>cancel -> The form was cancelled. Tell the asker that piece of information.</li>
* <li>result -> Data results being returned from a search, or some other query.</li>
* </ul>
*
* @return the form's type.
*/
public String getType() {
return dataForm.getType();
}
/**
* Sets instructions that explain how to fill out the form and what the form is about.
*
* @param instructions instructions that explain how to fill out the form.
*/
public void setInstructions(String instructions) {
dataForm.setInstructions(instructions);
}
/**
* Sets the description of the data. It is similar to the title on a web page or an X window.
* You can put a <title/> on either a form to fill out, or a set of data results.
*
* @param title description of the data.
*/
public void setTitle(String title) {
dataForm.setTitle(title);
}
/**
* Returns a DataForm that serves to send this Form to the server. If the form is of type
* submit, it may contain fields with no value. These fields will be remove since they only
* exist to assist the user while editing/completing the form in a UI.
*
* @return the wrapped DataForm.
*/
DataForm getDataFormToSend() {
if (isSubmitType()) {
// Answer a new form based on the values of this form
DataForm dataFormToSend = new DataForm(getType());
dataFormToSend.setInstructions(getInstructions());
dataFormToSend.setTitle(getTitle());
// Remove all the fields that have no answer
for(Iterator it=getFields();it.hasNext();) {
FormField field = (FormField)it.next();
if (field.getValues().hasNext()) {
dataFormToSend.addField(field);
}
}
return dataFormToSend;
}
return dataForm;
}
/**
* Returns true if the form is a form to fill out.
*
* @return if the form is a form to fill out.
*/
private boolean isFormType() {
return TYPE_FORM.equals(dataForm.getType());
}
/**
* Returns true if the form is a form to submit.
*
* @return if the form is a form to submit.
*/
private boolean isSubmitType() {
return TYPE_SUBMIT.equals(dataForm.getType());
}
/**
* Returns a new Form to submit the completed values. The new Form will include all the fields
* of the original form except for the fields of type FIXED. Only the HIDDEN fields will
* include the same value of the original form. The other fields of the new form MUST be
* completed. If a field remains with no answer when sending the completed form, then it won't
* be included as part of the completed form.<p>
*
* The reason why the fields with variables are included in the new form is to provide a model
* for binding with any UI. This means that the UIs will use the original form (of type
* "form") to learn how to render the form, but the UIs will bind the fields to the form of
* type submit.
*
* @return a Form to submit the completed values.
*/
public Form createAnswerForm() {
if (!isFormType()) {
throw new IllegalStateException("Only forms of type \"form\" could be answered");
}
// Create a new Form
Form form = new Form(TYPE_SUBMIT);
for (Iterator fields=getFields(); fields.hasNext();) {
FormField field = (FormField)fields.next();
// Add to the new form any type of field that includes a variable.
// Note: The fields of type FIXED are the only ones that don't specify a variable
if (field.getVariable() != null) {
form.addField(new FormField(field.getVariable()));
// Set the answer ONLY to the hidden fields
if (FormField.TYPE_HIDDEN.equals(field.getType())) {
// Since a hidden field could have many values we need to collect them
// in a list
List values = new ArrayList();
for (Iterator it=field.getValues();it.hasNext();) {
values.add((String)it.next());
}
form.setAnswer(field.getVariable(), values);
}
}
}
return form;
}
}
|
package ru.tuin;
/**
* @author Viktor Tulin
* @version 1
* @since 27.10.2016
*/
public class StartUI {
private Calculator calc;
private ConsoleInput input;
private InteractCalculator menu;
public StartUI(ConsoleInput input, Calculator calc, InteractCalculator menu) {
this.calc = calc;
this.input = input;
this.menu = menu;
}
/**
* method displays a menu until the user does not want to leave the program
*/
public void init() {
do {
menu.show();
int entry = this.input.ask("\nselect the menu item: ", menu.getAcceptableRange());
menu.select(Key.getKeyFromNumber(entry));
} while (!"y".equals(this.input.ask("To exit the program press (y) To continue work press (Enter): ")));
}
public static void main(String[] args) {
EngineerCalculator calc = new EngineerCalculator();
ConsoleInput input = new ValidateInput();
Print print = new Print();
EngineerInteractCalculator menu = new EngineerInteractCalculator(input, calc, print);
new StartUI(input, calc, menu).init();
}
}
|
package org.cyclops.structuredcrafting.craft.provider;
import com.mojang.authlib.GameProfile;
import net.minecraft.core.BlockPos;
import net.minecraft.core.Direction;
import net.minecraft.server.level.ServerLevel;
import net.minecraft.world.item.BlockItem;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.level.Level;
import net.minecraft.world.level.block.state.BlockState;
import net.minecraft.world.phys.BlockHitResult;
import net.minecraft.world.phys.Vec3;
import net.minecraftforge.common.util.FakePlayer;
import net.minecraftforge.items.CapabilityItemHandler;
import net.minecraftforge.items.IItemHandler;
import org.cyclops.cyclopscore.helper.BlockEntityHelpers;
import org.cyclops.cyclopscore.helper.ItemStackHelpers;
import org.cyclops.structuredcrafting.block.BlockStructuredCrafterConfig;
import java.util.Map;
import java.util.UUID;
import java.util.WeakHashMap;
/**
* World that can provide an itemstack.
* @author rubensworks
*/
public class WorldItemStackProvider implements IItemStackProvider {
private static GameProfile PROFILE = new GameProfile(UUID.fromString("41C82C87-7AfB-4024-BB57-13D2C99CAE78"), "[StructuredCrafting]");
private static final Map<ServerLevel, FakePlayer> FAKE_PLAYERS = new WeakHashMap<ServerLevel, FakePlayer>();
public static FakePlayer getFakePlayer(ServerLevel world) {
FakePlayer fakePlayer = FAKE_PLAYERS.get(world);
if (fakePlayer == null) {
fakePlayer = new FakePlayer(world, PROFILE);
FAKE_PLAYERS.put(world, fakePlayer);
}
return fakePlayer;
}
@Override
public boolean canProvideInput() {
return BlockStructuredCrafterConfig.canTakeInputsFromWorld;
}
@Override
public boolean canHandleOutput() {
return BlockStructuredCrafterConfig.canPlaceOutputsIntoWorld;
}
@Override
public boolean isValidForResults(Level world, BlockPos pos, Direction side) {
return world.isEmptyBlock(pos);
}
protected boolean hasEmptyItemHandler(Level world, BlockPos pos, Direction side) {
IItemHandler itemHandler = BlockEntityHelpers.getCapability(world, pos, side, CapabilityItemHandler.ITEM_HANDLER_CAPABILITY).orElse(null);
boolean emptyItemHandler = true;
if (itemHandler != null) {
for (int i = 0; i < itemHandler.getSlots(); i++) {
if (!itemHandler.extractItem(i, 1, true).isEmpty()) {
emptyItemHandler = false;
break;
}
}
}
return emptyItemHandler;
}
@Override
public boolean hasItemStack(Level world, BlockPos pos, Direction side) {
return !world.isEmptyBlock(pos) && hasEmptyItemHandler(world, pos, side);
}
@Override
public ItemStack getItemStack(Level world, BlockPos pos, Direction side) {
BlockState blockState = world.getBlockState(pos);
if(blockState != null && hasEmptyItemHandler(world, pos, side)) {
return blockState.getCloneItemStack(new BlockHitResult(new Vec3(0, 0, 0), side, pos, false), world, pos, getFakePlayer((ServerLevel) world));
}
return ItemStack.EMPTY;
}
@Override
public void reduceItemStack(Level world, BlockPos pos, Direction side, boolean simulate) {
if(!simulate) {
world.removeBlock(pos, false);
}
}
@Override
public boolean addItemStack(Level world, BlockPos pos, Direction side, ItemStack itemStack, boolean simulate) {
return setItemStack(world, pos, side, itemStack, simulate);
}
@Override
public boolean setItemStack(Level world, BlockPos pos, Direction side, ItemStack itemStack, boolean simulate) {
if(!simulate && itemStack.getItem() instanceof BlockItem) {
world.setBlockAndUpdate(pos, ((BlockItem) itemStack.getItem()).getBlock().defaultBlockState());
itemStack.shrink(1);
}
if(!simulate && itemStack.getCount() > 0) {
ItemStackHelpers.spawnItemStack(world, pos, itemStack);
}
return true;
}
}
|
package de.vanmar.android.yarrn.requests;
import android.app.Application;
import com.octo.android.robospice.persistence.DurationInMillis;
import com.octo.android.robospice.persistence.exception.SpiceException;
import com.octo.android.robospice.persistence.springandroid.json.gson.GsonObjectPersisterFactory;
import org.acra.ACRA;
import org.scribe.model.OAuthRequest;
import org.scribe.model.Response;
import de.vanmar.android.yarrn.YarrnPrefs_;
import de.vanmar.android.yarrn.ravelry.dts.ETaggable;
public abstract class AbstractRavelryGetRequest<T extends ETaggable> extends AbstractRavelryRequest<T> {
public static final long CACHE_DURATION = DurationInMillis.ONE_MINUTE;
private final GsonObjectPersisterFactory persisterFactory;
public AbstractRavelryGetRequest(Class<T> clazz, Application application, YarrnPrefs_ prefs) {
super(clazz, prefs, application);
try {
persisterFactory = new GsonObjectPersisterFactory(application);
} catch (SpiceException e) {
e.printStackTrace();
throw new RuntimeException(e);
}
}
@Override
public T loadDataFromNetwork() throws Exception {
final OAuthRequest request = getRequest();
ACRA.getErrorReporter().putCustomData("lastUrl", getCacheKey().toString());
/*T dataFromCache = persisterFactory.createObjectPersister(getResultType()).loadDataFromCache(getCacheKey(), DurationInMillis.ALWAYS_RETURNED);
if (dataFromCache != null) {
request.addHeader("If-None-Match", dataFromCache.getETag());
}*/
final Response response = executeRequest(request);
/*if (response.getCode() == 304) {
return dataFromCache;
} else {*/
T result = parseResult(response.getBody());
result.setETag(response.getHeader("ETag"));
return result;
}
protected abstract T parseResult(String responseBody);
protected abstract OAuthRequest getRequest();
public Object getCacheKey() {
OAuthRequest request = getRequest();
return request.getCompleteUrl();
}
}
|
package org.jenkinsci.plugins.docker.commons.impl;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import javax.annotation.Nonnull;
import org.apache.commons.lang.StringUtils;
import org.jenkinsci.plugins.docker.commons.credentials.KeyMaterial;
import org.jenkinsci.plugins.docker.commons.credentials.KeyMaterialFactory;
import org.kohsuke.accmod.Restricted;
import org.kohsuke.accmod.restrictions.NoExternalUse;
import hudson.AbortException;
import hudson.EnvVars;
import hudson.FilePath;
import hudson.Launcher;
import hudson.model.TaskListener;
import hudson.util.ArgumentListBuilder;
import net.sf.json.JSONObject;
/**
* Logs you in to a Docker registry.
*/
@Restricted(NoExternalUse.class)
public class RegistryKeyMaterialFactory extends KeyMaterialFactory {
private static final String DOCKER_CONFIG_FILENAME = "config.json";
private static final String[] BLACKLISTED_PROPERTIES = { "auths", "credsStore" };
private final @Nonnull String username;
private final @Nonnull String password;
private final @Nonnull URL endpoint;
private final @Nonnull Launcher launcher;
private final @Nonnull EnvVars env;
private final @Nonnull TaskListener listener;
private final @Nonnull String dockerExecutable;
public RegistryKeyMaterialFactory(@Nonnull String username, @Nonnull String password, @Nonnull URL endpoint, @Nonnull Launcher launcher, @Nonnull EnvVars env, @Nonnull TaskListener listener, @Nonnull String dockerExecutable) {
this.username = username;
this.password = password;
this.endpoint = endpoint;
this.launcher = launcher;
this.env = env;
this.listener = listener;
this.dockerExecutable = dockerExecutable;
}
@Override
public KeyMaterial materialize() throws IOException, InterruptedException {
FilePath dockerConfig = createSecretsDirectory();
// read the existing docker config file, which might hold some important settings (e.b. proxies)
FilePath configJsonPath = FilePath.getHomeDirectory(this.launcher.getChannel()).child(".docker").child(DOCKER_CONFIG_FILENAME);
if (configJsonPath.exists()) {
String configJson = configJsonPath.readToString();
if (StringUtils.isNotBlank(configJson)) {
launcher.getListener().getLogger().print("Using the existing docker config file.");
JSONObject json = JSONObject.fromObject(configJson);
for (String property : BLACKLISTED_PROPERTIES) {
Object value = json.remove(property);
if (value != null) {
launcher.getListener().getLogger().print("Removing blacklisted property: " + property);
}
}
dockerConfig.child(DOCKER_CONFIG_FILENAME).write(json.toString(), StandardCharsets.UTF_8.name());
}
}
try {
EnvVars envWithConfig = new EnvVars(env);
envWithConfig.put("DOCKER_CONFIG", dockerConfig.getRemote());
if (launcher.launch().cmds(new ArgumentListBuilder(dockerExecutable, "login", "-u", username, "--password-stdin").add(endpoint)).envs(envWithConfig).stdin(new ByteArrayInputStream(password.getBytes("UTF-8"))).stdout(listener).join() != 0) {
throw new AbortException("docker login failed");
}
} catch (IOException | InterruptedException x) {
try {
dockerConfig.deleteRecursive();
} catch (Exception x2) {
x.addSuppressed(x2);
}
throw x;
}
return new RegistryKeyMaterial(dockerConfig, new EnvVars("DOCKER_CONFIG", dockerConfig.getRemote()));
}
private static class RegistryKeyMaterial extends KeyMaterial {
private final FilePath dockerConfig;
RegistryKeyMaterial(FilePath dockerConfig, EnvVars envVars) {
super(envVars);
this.dockerConfig = dockerConfig;
}
@Override
public void close() throws IOException {
try {
dockerConfig.deleteRecursive();
} catch (InterruptedException x) {
// TODO would better have been thrown from KeyMaterial.close to begin with
throw new IOException(x);
}
}
}
}
|
package makeithappen.vaadin.app.internal;
import org.eclipse.emf.ecp.makeithappen.model.task.TaskFactory;
import org.eclipse.emf.ecp.makeithappen.model.task.User;
import org.eclipse.emf.ecp.view.core.vaadin.ECPVaadinView;
import org.eclipse.emf.ecp.view.core.vaadin.ECPVaadinViewRenderer;
import org.lunifera.runtime.web.vaadin.databinding.VaadinObservables;
import com.vaadin.annotations.Push;
import com.vaadin.annotations.Theme;
import com.vaadin.server.VaadinRequest;
import com.vaadin.ui.UI;
import com.vaadin.ui.themes.ValoTheme;
// @PreserveOnRefresh
@Theme(ValoTheme.THEME_NAME)
// @Theme(Reindeer.THEME_NAME)
@Push
/**
* Render the eObject.
* @author Dennis Melzer
*
*/
public class VaadinMainUI extends UI {
private static final long serialVersionUID = 1L;
final static User USER = TaskFactory.eINSTANCE.createUser();
@Override
protected void init(VaadinRequest request) {
getPage().setTitle("Test Vaadin Valo");
VaadinObservables.activateRealm(this);
final ECPVaadinView ecpVaadinView = ECPVaadinViewRenderer.INSTANCE.render(USER);
setContent(ecpVaadinView.getComponent());
}
@Override
protected void refresh(VaadinRequest request) {
}
}
|
package org.openhab.binding.heos.internal.discovery;
import static org.openhab.binding.heos.HeosBindingConstants.*;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import org.eclipse.jdt.annotation.NonNullByDefault;
import org.eclipse.jdt.annotation.Nullable;
import org.eclipse.smarthome.config.discovery.DiscoveryResult;
import org.eclipse.smarthome.config.discovery.DiscoveryResultBuilder;
import org.eclipse.smarthome.config.discovery.upnp.UpnpDiscoveryParticipant;
import org.eclipse.smarthome.core.thing.ThingTypeUID;
import org.eclipse.smarthome.core.thing.ThingUID;
import org.jupnp.model.meta.DeviceDetails;
import org.jupnp.model.meta.ManufacturerDetails;
import org.jupnp.model.meta.ModelDetails;
import org.jupnp.model.meta.RemoteDevice;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* The {@link HeosDiscoveryParticipant} discovers the HEOS Player of the
* network via an UPnP interface.
*
* @author Johannes Einig - Initial contribution
*/
@NonNullByDefault
public class HeosDiscoveryParticipant implements UpnpDiscoveryParticipant {
private Logger logger = LoggerFactory.getLogger(HeosDiscoveryParticipant.class);
@Override
public Set<ThingTypeUID> getSupportedThingTypeUIDs() {
return Collections.singleton(THING_TYPE_BRIDGE);
}
@Override
public @Nullable DiscoveryResult createResult(RemoteDevice device) {
ThingUID uid = getThingUID(device);
if (uid != null) {
Map<String, Object> properties = new HashMap<>(2);
properties.put(HOST, device.getIdentity().getDescriptorURL().getHost());
properties.put(NAME, device.getDetails().getModelDetails().getModelName());
DiscoveryResult result = DiscoveryResultBuilder.create(uid).withProperties(properties)
.withLabel(device.getDetails().getFriendlyName()).withRepresentationProperty(PLAYER_TYPE).build();
logger.info("Found HEOS device with UID: {}", uid.getAsString());
return result;
}
return null;
}
@Override
public @Nullable ThingUID getThingUID(RemoteDevice device) {
Optional<RemoteDevice> optDevice = Optional.ofNullable(device);
String modelName = optDevice.map(RemoteDevice::getDetails).map(DeviceDetails::getModelDetails)
.map(ModelDetails::getModelName).orElse("UNKNOWN");
String modelManufacturer = optDevice.map(RemoteDevice::getDetails).map(DeviceDetails::getManufacturerDetails)
.map(ManufacturerDetails::getManufacturer).orElse("UNKNOWN");
if (modelManufacturer.equals("Denon")) {
if (modelName.startsWith("HEOS") || modelName.endsWith("H")) {
if (device.getType().getType().startsWith("ACT")) {
return new ThingUID(THING_TYPE_BRIDGE,
optDevice.get().getIdentity().getUdn().getIdentifierString());
}
}
}
return null;
// optDevice.map(RemoteDevice::getDetails).map(DeviceDetails::getModelDetails).map(ModelDetails::getModelName)
// .ifPresent(modelName -> {
// optDevice.map(RemoteDevice::getDetails).map(DeviceDetails::getManufacturerDetails)
// .map(ManufacturerDetails::getManufacturer).ifPresent(modelManufacturer -> {
// if (modelManufacturer.equals("Denon")) {
// if (modelName.startsWith("HEOS") || modelName.endsWith("H")) {
// if (device.getType().getType().startsWith("ACT")) {
// thingUID = new ThingUID(THING_TYPE_BRIDGE,
// optDevice.get().getIdentity().getUdn().getIdentifierString());
// return thingUID;
// DeviceDetails details = device.getDetails();
// if (details != null) {
// ModelDetails modelDetails = details.getModelDetails();
// ManufacturerDetails modelManufacturerDetails = details.getManufacturerDetails();
// if (modelDetails != null && modelManufacturerDetails != null) {
// String modelName = modelDetails.getModelName();
// String modelManufacturer = modelManufacturerDetails.getManufacturer();
// if (modelName != null && modelManufacturer != null) {
// if (modelManufacturer.equals("Denon")) {
// if (modelName.startsWith("HEOS") || modelName.endsWith("H")) {
// if (device.getType().getType().startsWith("ACT")) {
// return new ThingUID(THING_TYPE_BRIDGE,
// device.getIdentity().getUdn().getIdentifierString());
// return null;
}
}
|
package org.eclipse.persistence.exceptions.i18n;
import java.text.MessageFormat;
import java.util.Locale;
import java.util.ResourceBundle;
import java.util.Vector;
import org.eclipse.persistence.internal.helper.ConversionManager;
import org.eclipse.persistence.internal.helper.Helper;
public class ExceptionMessageGenerator {
/**
* Return the loader for loading the resource bundles.
*/
public static ClassLoader getLoader() {
ClassLoader loader = ExceptionMessageGenerator.class.getClassLoader();
if (loader == null) {
loader = ConversionManager.getDefaultManager().getLoader();
}
return loader;
}
/**
* Return the message for the given exception class and error number.
*/
public static String buildMessage(Class exceptionClass, int errorNumber, Object[] arguments) {
final String CR = System.getProperty("line.separator");
String shortClassName = Helper.getShortClassName(exceptionClass);
String message = "";
ResourceBundle bundle = null;
// JDK 1.1 MessageFormat can't handle null arguments
for (int i = 0; i < arguments.length; i++) {
if (arguments[i] == null) {
arguments[i] = "null";
}
}
bundle = ResourceBundle.getBundle("org.eclipse.persistence.exceptions.i18n." + shortClassName + "Resource", Locale.getDefault(), getLoader());
try {
message = bundle.getString(String.valueOf(errorNumber));
} catch (java.util.MissingResourceException mre) {
// Found bundle, but couldn't find exception translation.
// Get the current language's NoExceptionTranslationForThisLocale message.
bundle = ResourceBundle.getBundle("org.eclipse.persistence.exceptions.i18n.ExceptionResource", Locale.getDefault(), getLoader());
String noTranslationMessage = bundle.getString("NoExceptionTranslationForThisLocale");
Object[] args = { CR };
return format(message, arguments) + format(noTranslationMessage, args);
}
return format(message, arguments);
}
/**
* Return the formatted message for the given exception class and error number.
*/
//Bug#4619864 Catch any exception during formatting and try to throw that exception. One possibility is toString() to an argument
protected static String format(String message, Object[] arguments) {
try {
return MessageFormat.format(message, arguments);
} catch (Exception ex) {
ResourceBundle bundle = null;
bundle = ResourceBundle.getBundle("org.eclipse.persistence.exceptions.i18n.ExceptionResource", Locale.getDefault(), getLoader());
String errorMessage = bundle.getString("ErrorFormattingMessage");
Vector vec = new Vector();
if (arguments != null) {
for (int index = 0; index < arguments.length; index++) {
try {
vec.add(arguments[index].toString());
} catch (Exception ex2) {
vec.add(ex2);
}
}
}
return MessageFormat.format(errorMessage, new Object[] {message, vec});
}
}
/**
* Get one of the generic headers used for the exception's toString().
*
* E.g., "EXCEPTION DESCRIPTION: ", "ERROR CODE: ", etc.
*/
public static String getHeader(String headerLabel) {
ResourceBundle bundle = null;
try {
bundle = ResourceBundle.getBundle("org.eclipse.persistence.exceptions.i18n.ExceptionResource", Locale.getDefault(), getLoader());
return bundle.getString(headerLabel);
} catch (java.util.MissingResourceException mre) {
return "[" + headerLabel + "]";
}
}
}
|
package org.eclipse.persistence.internal.oxm.record;
import java.util.ArrayList;
import java.util.List;
import javax.xml.namespace.QName;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamReader;
import org.eclipse.persistence.internal.oxm.record.namespaces.UnmarshalNamespaceContext;
import org.eclipse.persistence.oxm.XMLConstants;
import org.xml.sax.Attributes;
import org.xml.sax.ContentHandler;
import org.xml.sax.ErrorHandler;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.SAXNotRecognizedException;
import org.xml.sax.SAXNotSupportedException;
import org.xml.sax.ext.LexicalHandler;
/**
* Convert and XMLStreamReader into SAX events.
*/
public class XMLStreamReaderReader extends XMLReader {
private ContentHandler contentHandler;
private LexicalHandler lexicalHandler;
private ErrorHandler errorHandler;
private int depth = 0;
public XMLStreamReaderReader() {
}
@Override
public ContentHandler getContentHandler() {
return contentHandler;
}
@Override
public void setContentHandler(ContentHandler aContentHandler) {
this.contentHandler = aContentHandler;
}
@Override
public ErrorHandler getErrorHandler() {
return errorHandler;
}
@Override
public void setErrorHandler(ErrorHandler anErrorHandler) {
this.errorHandler = anErrorHandler;
}
@Override
public void setProperty (String name, Object value) throws SAXNotRecognizedException, SAXNotSupportedException {
if(name.equals("http://xml.org/sax/properties/lexical-handler")) {
lexicalHandler = (LexicalHandler)value;
}
}
@Override
public void parse(InputSource input) throws SAXException {
if(input instanceof XMLStreamReaderInputSource) {
XMLStreamReader xmlStreamReader = ((XMLStreamReaderInputSource) input).getXmlStreamReader();
parse(xmlStreamReader);
}
}
@Override
public void parse(InputSource input, SAXUnmarshallerHandler saxUnmarshallerHandler) throws SAXException {
if(input instanceof XMLStreamReaderInputSource) {
XMLStreamReader xmlStreamReader = ((XMLStreamReaderInputSource) input).getXmlStreamReader();
saxUnmarshallerHandler.setUnmarshalNamespaceResolver(new UnmarshalNamespaceContext(xmlStreamReader));
parse(xmlStreamReader);
}
}
public void parse(String systemId) throws SAXException {}
private void parse(XMLStreamReader xmlStreamReader) throws SAXException {
try{
parseEvent(xmlStreamReader);
while(depth > 0 && xmlStreamReader.hasNext()) {
xmlStreamReader.next();
parseEvent(xmlStreamReader);
}
}catch(XMLStreamException e) {
throw new RuntimeException(e);
}
}
private void parseEvent(XMLStreamReader xmlStreamReader) throws SAXException {
if(null == getContentHandler()) {
return;
}
switch (xmlStreamReader.getEventType()) {
case XMLStreamReader.ATTRIBUTE: {
break;
}
case XMLStreamReader.CDATA: {
if(null == lexicalHandler) {
getContentHandler().characters(xmlStreamReader.getTextCharacters(), xmlStreamReader.getTextStart(), xmlStreamReader.getTextLength());
} else {
lexicalHandler.startCDATA();
getContentHandler().characters(xmlStreamReader.getTextCharacters(), xmlStreamReader.getTextStart(), xmlStreamReader.getTextLength());
lexicalHandler.endCDATA();
}
break;
}
case XMLStreamReader.CHARACTERS: {
getContentHandler().characters(xmlStreamReader.getTextCharacters(), xmlStreamReader.getTextStart(), xmlStreamReader.getTextLength());
break;
}
case XMLStreamReader.COMMENT: {
if(null != lexicalHandler) {
lexicalHandler.comment(xmlStreamReader.getTextCharacters(), xmlStreamReader.getTextStart(), xmlStreamReader.getTextLength());
}
break;
}
case XMLStreamReader.DTD: {
break;
}
case XMLStreamReader.END_DOCUMENT: {
depth
getContentHandler().endDocument();
return;
}
case XMLStreamReader.END_ELEMENT: {
depth
String prefix = xmlStreamReader.getPrefix();
if(null == prefix || prefix.length() == 0) {
getContentHandler().endElement(xmlStreamReader.getNamespaceURI(), xmlStreamReader.getLocalName(), xmlStreamReader.getLocalName());
} else {
getContentHandler().endElement(xmlStreamReader.getNamespaceURI(), xmlStreamReader.getLocalName(), prefix + XMLConstants.COLON + xmlStreamReader.getLocalName());
}
break;
}
case XMLStreamReader.ENTITY_DECLARATION: {
break;
}
case XMLStreamReader.ENTITY_REFERENCE: {
break;
}
case XMLStreamReader.NAMESPACE: {
break;
}
case XMLStreamReader.NOTATION_DECLARATION: {
break;
}
case XMLStreamReader.PROCESSING_INSTRUCTION: {
getContentHandler().processingInstruction(xmlStreamReader.getPITarget(), xmlStreamReader.getPIData());
break;
}
case XMLStreamReader.SPACE: {
char[] characters = xmlStreamReader.getTextCharacters();
getContentHandler().characters(characters, 0, characters.length);
break;
}
case XMLStreamReader.START_DOCUMENT: {
depth++;
getContentHandler().startDocument();
break;
}
case XMLStreamReader.START_ELEMENT: {
depth++;
String prefix = xmlStreamReader.getPrefix();
if(null == prefix || prefix.length() == 0) {
getContentHandler().startElement(xmlStreamReader.getNamespaceURI(), xmlStreamReader.getLocalName(), xmlStreamReader.getLocalName(), new IndexedAttributeList(xmlStreamReader));
} else {
getContentHandler().startElement(xmlStreamReader.getNamespaceURI(), xmlStreamReader.getLocalName(), prefix + XMLConstants.COLON + xmlStreamReader.getLocalName(), new IndexedAttributeList(xmlStreamReader));
}
break;
}
}
}
private static class IndexedAttributeList implements Attributes {
private List<Attribute> attributes;
public IndexedAttributeList(XMLStreamReader xmlStreamReader) {
int namespaceCount = xmlStreamReader.getNamespaceCount();
int attributeCount = xmlStreamReader.getAttributeCount();
attributes = new ArrayList<Attribute>(attributeCount + namespaceCount);
for(int x=0; x<namespaceCount; x++) {
String uri = XMLConstants.XMLNS_URL;
String localName = xmlStreamReader.getNamespacePrefix(x);
String qName;
if(null == localName || localName.length() == 0) {
localName = XMLConstants.XMLNS;
qName = XMLConstants.XMLNS;
} else {
qName = XMLConstants.XMLNS + XMLConstants.COLON + localName;
}
String value = xmlStreamReader.getNamespaceURI(x);
attributes.add(new Attribute(uri, localName, qName, value));
}
for(int x=0; x<attributeCount; x++) {
String uri = xmlStreamReader.getAttributeNamespace(x);
String localName = xmlStreamReader.getAttributeLocalName(x);
String prefix = xmlStreamReader.getAttributePrefix(x);
String qName;
if(null == prefix || prefix.length() == 0) {
qName = localName;
} else {
qName = prefix + XMLConstants.COLON + localName;
}
String value = xmlStreamReader.getAttributeValue(x);
attributes.add(new Attribute(uri, localName, qName, value));
}
}
public int getIndex(String qName) {
if(null == qName) {
return -1;
}
int index = 0;
for(Attribute attribute : attributes) {
if(qName.equals(attribute.getName())) {
return index;
}
index++;
}
return -1;
}
public int getIndex(String uri, String localName) {
if(null == localName) {
return -1;
}
int index = 0;
for(Attribute attribute : attributes) {
QName testQName = new QName(uri, localName);
if(attribute.getQName().equals(testQName)) {
return index;
}
index++;
}
return -1;
}
public int getLength() {
return attributes.size();
}
public String getLocalName(int index) {
return attributes.get(index).getQName().getLocalPart();
}
public String getQName(int index) {
return attributes.get(index).getName();
}
public String getType(int index) {
return XMLConstants.CDATA;
}
public String getType(String name) {
return XMLConstants.CDATA;
}
public String getType(String uri, String localName) {
return XMLConstants.CDATA;
}
public String getURI(int index) {
return attributes.get(index).getQName().getNamespaceURI();
}
public String getValue(int index) {
return attributes.get(index).getValue();
}
public String getValue(String qName) {
int index = getIndex(qName);
if(-1 == index) {
return null;
}
return attributes.get(index).getValue();
}
public String getValue(String uri, String localName) {
int index = getIndex(uri, localName);
if(-1 == index) {
return null;
}
return attributes.get(index).getValue();
}
}
private static class Attribute {
private QName qName;
private String name;
private String value;
public Attribute(String uri, String localName, String name, String value) {
this.qName = new QName(uri, localName);
this.name = name;
this.value = value;
}
public QName getQName() {
return qName;
}
public String getName() {
return name;
}
public String getValue() {
return value;
}
}
}
|
package net.java.sip.communicator.impl.protocol.yahoo;
import java.io.*;
import net.java.sip.communicator.service.protocol.*;
import net.java.sip.communicator.service.protocol.event.*;
import net.java.sip.communicator.util.*;
import ymsg.network.*;
import ymsg.network.event.*;
/**
* An implementation of the protocol provider service over the Yahoo protocol
*
* @author Damian Minkov
*/
public class ProtocolProviderServiceYahooImpl
extends AbstractProtocolProviderService
{
private static final Logger logger =
Logger.getLogger(ProtocolProviderServiceYahooImpl.class);
private YahooSession yahooSession = null;
/**
* indicates whether or not the provider is initialized and ready for use.
*/
private boolean isInitialized = false;
/**
* We use this to lock access to initialization.
*/
private final Object initializationLock = new Object();
/**
* The identifier of the account that this provider represents.
*/
private AccountID accountID = null;
/**
* Used when we need to re-register
*/
private SecurityAuthority authority = null;
private OperationSetPersistentPresenceYahooImpl persistentPresence = null;
private OperationSetTypingNotificationsYahooImpl typingNotifications = null;
/**
* The logo corresponding to the msn protocol.
*/
private ProtocolIconYahooImpl yahooIcon
= new ProtocolIconYahooImpl();
/**
* Returns the state of the registration of this protocol provider
* @return the <tt>RegistrationState</tt> that this provider is
* currently in or null in case it is in a unknown state.
*/
public RegistrationState getRegistrationState()
{
if(yahooSession != null &&
yahooSession.getSessionStatus() == StatusConstants.MESSAGING)
return RegistrationState.REGISTERED;
else
return RegistrationState.UNREGISTERED;
}
/**
* Starts the registration process. Connection details such as
* registration server, user name/number are provided through the
* configuration service through implementation specific properties.
*
* @param authority the security authority that will be used for resolving
* any security challenges that may be returned during the
* registration or at any moment while wer're registered.
* @throws OperationFailedException with the corresponding code it the
* registration fails for some reason (e.g. a networking error or an
* implementation problem).
*/
public void register(final SecurityAuthority authority)
throws OperationFailedException
{
if(authority == null)
throw new IllegalArgumentException(
"The register method needs a valid non-null authority impl "
+ " in order to be able and retrieve passwords.");
this.authority = authority;
connectAndLogin(authority, SecurityAuthority.AUTHENTICATION_REQUIRED);
}
/**
* Connects and logins to the server
* @param authority SecurityAuthority
* @param authReasonCode the authentication reason code, which should
* indicate why are making an authentication request
* @throws XMPPException if we cannot connect to the server - network problem
* @throws OperationFailedException if login parameters
* as server port are not correct
*/
private void connectAndLogin( SecurityAuthority authority,
int authReasonCode)
throws OperationFailedException
{
synchronized(initializationLock)
{
//verify whether a password has already been stored for this account
String password = YahooActivator.
getProtocolProviderFactory().loadPassword(getAccountID());
//decode
if (password == null)
{
//create a default credentials object
UserCredentials credentials = new UserCredentials();
credentials.setUserName(getAccountID().getUserID());
//request a password from the user
credentials = authority.obtainCredentials(
ProtocolNames.YAHOO,
credentials,
authReasonCode);
//extract the password the user passed us.
char[] pass = credentials.getPassword();
// the user didn't provide us a password (canceled the operation)
if(pass == null)
{
fireRegistrationStateChanged(
getRegistrationState(),
RegistrationState.UNREGISTERED,
RegistrationStateChangeEvent.REASON_USER_REQUEST, "");
return;
}
password = new String(pass);
if (credentials.isPasswordPersistent())
{
YahooActivator.getProtocolProviderFactory()
.storePassword(getAccountID(), password);
}
}
yahooSession = new YahooSession();
yahooSession.addSessionListener(new YahooConnectionListener());
try
{
fireRegistrationStateChanged(
getRegistrationState(),
RegistrationState.REGISTERING,
RegistrationStateChangeEvent.REASON_NOT_SPECIFIED, null);
yahooSession.login(getAccountID().getUserID(), password);
if(yahooSession.getSessionStatus()==StatusConstants.MESSAGING)
{
persistentPresence.fireProviderStatusChangeEvent(
persistentPresence.getPresenceStatus(),
persistentPresence.yahooStatusToPresenceStatus(
yahooSession.getStatus()));
fireRegistrationStateChanged(
getRegistrationState(),
RegistrationState.REGISTERED,
RegistrationStateChangeEvent.REASON_NOT_SPECIFIED, null);
}
else
{
fireRegistrationStateChanged(
getRegistrationState(),
RegistrationState.UNREGISTERED,
RegistrationStateChangeEvent.REASON_NOT_SPECIFIED, null);
}
}
catch (LoginRefusedException ex)
{
if(ex.getStatus() == StatusConstants.STATUS_BADUSERNAME)
{
fireRegistrationStateChanged(
getRegistrationState(),
RegistrationState.AUTHENTICATION_FAILED,
RegistrationStateChangeEvent.REASON_NON_EXISTING_USER_ID,
null);
reregister(SecurityAuthority.WRONG_USERNAME);
}
else if(ex.getStatus() == StatusConstants.STATUS_BAD)
{
YahooActivator.getProtocolProviderFactory()
.storePassword(getAccountID(), null);
fireRegistrationStateChanged(
getRegistrationState(),
RegistrationState.AUTHENTICATION_FAILED,
RegistrationStateChangeEvent.REASON_AUTHENTICATION_FAILED,
null);
// Try to re-register and ask the user to retype the password.
reregister(SecurityAuthority.WRONG_PASSWORD);
}
else if(ex.getStatus() == StatusConstants.STATUS_LOCKED)
{
fireRegistrationStateChanged(
getRegistrationState(),
RegistrationState.AUTHENTICATION_FAILED,
RegistrationStateChangeEvent.REASON_RECONNECTION_RATE_LIMIT_EXCEEDED,
null);
}
}
catch (IOException ex)
{
fireRegistrationStateChanged(
getRegistrationState(),
RegistrationState.CONNECTION_FAILED,
RegistrationStateChangeEvent.REASON_NOT_SPECIFIED, null);
}
}
}
/**
* Reconnects if fails fire connection failed.
* @param reasonCode the appropriate <tt>SecurityAuthority</tt> reasonCode,
* which would specify the reason for which we're re-calling the login.
*/
void reregister(int reasonCode)
{
try
{
connectAndLogin(authority, reasonCode);
}
catch (OperationFailedException ex)
{
fireRegistrationStateChanged(
getRegistrationState(),
RegistrationState.CONNECTION_FAILED,
RegistrationStateChangeEvent.REASON_NOT_SPECIFIED, null);
}
}
/**
* Ends the registration of this protocol provider with the service.
*/
public void unregister()
{
unregister(true);
}
/**
* Unregister and fire the event if requested
* @param fireEvent boolean
*/
void unregister(boolean fireEvent)
{
RegistrationState currRegState = getRegistrationState();
try
{
if((yahooSession != null)
&& (yahooSession.getSessionStatus() == StatusConstants.MESSAGING))
yahooSession.logout();
}
catch(Exception ex)
{
logger.error("Cannot logout! ", ex);
}
yahooSession = null;
if(fireEvent)
fireRegistrationStateChanged(
currRegState,
RegistrationState.UNREGISTERED,
RegistrationStateChangeEvent.REASON_USER_REQUEST,
null);
}
/**
* Returns the short name of the protocol that the implementation of this
* provider is based upon (like SIP, Msn, ICQ/AIM, or others for
* example).
*
* @return a String containing the short name of the protocol this
* service is taking care of.
*/
public String getProtocolName()
{
return ProtocolNames.YAHOO;
}
/**
* Initialized the service implementation, and puts it in a sate where it
* could interoperate with other services. It is strongly recomended that
* properties in this Map be mapped to property names as specified by
* <tt>AccountProperties</tt>.
*
* @param screenname the account id/uin/screenname of the account that
* we're about to create
* @param accountID the identifier of the account that this protocol
* provider represents.
*
* @see net.java.sip.communicator.service.protocol.AccountID
*/
protected void initialize(String screenname,
AccountID accountID)
{
synchronized(initializationLock)
{
this.accountID = accountID;
addSupportedOperationSet(
OperationSetInstantMessageTransform.class,
new OperationSetInstantMessageTransformImpl());
//initialize the presence operationset
persistentPresence
= new OperationSetPersistentPresenceYahooImpl(this);
addSupportedOperationSet(
OperationSetPersistentPresence.class,
persistentPresence);
//register it once again for those that simply need presence
addSupportedOperationSet(
OperationSetPresence.class,
persistentPresence);
//initialize the IM operation set
addSupportedOperationSet(
OperationSetBasicInstantMessaging.class,
new OperationSetBasicInstantMessagingYahooImpl(this));
//initialize the multi user chat operation set
addSupportedOperationSet(
OperationSetAdHocMultiUserChat.class,
new OperationSetAdHocMultiUserChatYahooImpl(this));
//initialize the typing notifications operation set
typingNotifications
= new OperationSetTypingNotificationsYahooImpl(this);
addSupportedOperationSet(
OperationSetTypingNotifications.class,
typingNotifications);
addSupportedOperationSet(
OperationSetFileTransfer.class,
new OperationSetFileTransferYahooImpl(this));
isInitialized = true;
}
}
/**
* Makes the service implementation close all open sockets and release
* any resources that it might have taken and prepare for
* shutdown/garbage collection.
*/
public void shutdown()
{
synchronized(initializationLock){
unregister(false);
yahooSession = null;
isInitialized = false;
}
}
/**
* Returns true if the provider service implementation is initialized and
* ready for use by other services, and false otherwise.
*
* @return true if the provider is initialized and ready for use and false
* otherwise
*/
public boolean isInitialized()
{
return isInitialized;
}
/**
* Returns the AccountID that uniquely identifies the account represented
* by this instance of the ProtocolProviderService.
* @return the id of the account represented by this provider.
*/
public AccountID getAccountID()
{
return accountID;
}
/**
* Returns the Yahoo<tt>Session</tt>opened by this provider
* @return a reference to the <tt>Session</tt> last opened by this
* provider.
*/
YahooSession getYahooSession()
{
return yahooSession;
}
/**
* Creates a RegistrationStateChange event corresponding to the specified
* old and new states and notifies all currently registered listeners.
*
* @param oldState the state that the provider had before the change
* occurred
* @param newState the state that the provider is currently in.
* @param reasonCode a value corresponding to one of the REASON_XXX fields
* of the RegistrationStateChangeEvent class, indicating the reason for
* this state transition.
* @param reason a String further explaining the reason code or null if
* no such explanation is necessary.
*/
public void fireRegistrationStateChanged( RegistrationState oldState,
RegistrationState newState,
int reasonCode,
String reason)
{
if(newState.equals(RegistrationState.UNREGISTERED) ||
newState.equals(RegistrationState.CONNECTION_FAILED))
{
unregister(false);
yahooSession = null;
}
super.fireRegistrationStateChanged(oldState, newState, reasonCode, reason);
}
/**
* Listens when we are logged in the server
* or incoming exception in the lib impl.
*/
private class YahooConnectionListener
extends SessionAdapter
{
/**
* Yahoo has logged us off the system, or the connection was lost
**/
public void connectionClosed(SessionEvent ev)
{
unregister(true);
if(isRegistered())
fireRegistrationStateChanged(
getRegistrationState(),
RegistrationState.CONNECTION_FAILED,
RegistrationStateChangeEvent.REASON_NOT_SPECIFIED, null);
}
public void inputExceptionThrown(SessionExceptionEvent ev)
{
if(ev.getException() instanceof YMSG9BadFormatException)
{
logger.error("Yahoo protocol exception occured exception",
ev.getException());
logger.error("Yahoo protocol exception occured exception cause",
ev.getException().getCause());
}
else
logger.error(
"Yahoo protocol exception occured", ev.getException());
unregister(false);
if(isRegistered())
fireRegistrationStateChanged(
getRegistrationState(),
RegistrationState.UNREGISTERED,
RegistrationStateChangeEvent.REASON_INTERNAL_ERROR, null);
}
}
/**
* Returns the yahoo protocol icon.
* @return the yahoo protocol icon
*/
public ProtocolIcon getProtocolIcon()
{
return yahooIcon;
}
}
|
package gobblin.ingestion.google.adwords;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.zip.GZIPInputStream;
import org.apache.commons.lang3.tuple.Pair;
import org.joda.time.DateTime;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;
import com.google.api.ads.adwords.lib.client.AdWordsSession;
import com.google.api.ads.adwords.lib.client.reporting.ReportingConfiguration;
import com.google.api.ads.adwords.lib.jaxb.v201609.DateRange;
import com.google.api.ads.adwords.lib.jaxb.v201609.DownloadFormat;
import com.google.api.ads.adwords.lib.jaxb.v201609.ReportDefinition;
import com.google.api.ads.adwords.lib.jaxb.v201609.ReportDefinitionDateRangeType;
import com.google.api.ads.adwords.lib.jaxb.v201609.ReportDefinitionReportType;
import com.google.api.ads.adwords.lib.jaxb.v201609.Selector;
import com.google.api.ads.adwords.lib.utils.ReportDownloadResponse;
import com.google.api.ads.adwords.lib.utils.ReportDownloadResponseException;
import com.google.api.ads.adwords.lib.utils.ReportException;
import com.google.api.ads.adwords.lib.utils.v201609.ReportDownloader;
import com.google.api.ads.common.lib.exception.ValidationException;
import com.google.api.client.util.BackOff;
import com.google.api.client.util.ExponentialBackOff;
import com.google.gson.JsonArray;
import com.google.gson.JsonParser;
import com.opencsv.CSVParser;
import lombok.extern.slf4j.Slf4j;
import gobblin.configuration.WorkUnitState;
import gobblin.source.extractor.extract.LongWatermark;
@Slf4j
public class GoogleAdWordsReportDownloader {
private final static CSVParser splitter = new CSVParser(',', '"', '\\');
private final static int SIZE = 4096; //Buffer size for unzipping stream.
private final boolean _skipReportHeader;
private final boolean _skipColumnHeader;
private final boolean _skipReportSummary;
private final boolean _includeZeroImpressions;
private final boolean _useRawEnumValues;
private final AdWordsSession _rootSession;
private final ExponentialBackOff.Builder backOffBuilder =
new ExponentialBackOff.Builder().setMaxElapsedTimeMillis(1000 * 60 * 5);
private final List<String> _columnNames;
private final ReportDefinitionReportType _reportType;
private final ReportDefinitionDateRangeType _dateRangeType;
private final String _startDate;
private final String _endDate;
private final boolean _dailyPartition;
private final static DateTimeFormatter dateFormatter = DateTimeFormat.forPattern("yyyyMMdd");
private final static DateTimeFormatter watermarkFormatter = DateTimeFormat.forPattern("yyyyMMddHHmmss");
/**
* debug in FILE mode is to download reports in file format directly
*/
private final String _debugFileOutputPath;
/**
* debug in STRING mode is to download reports in strings, then concate and convert all strings to files.
*/
private final String _debugStringOutputPath;
public GoogleAdWordsReportDownloader(AdWordsSession rootSession, WorkUnitState state,
ReportDefinitionReportType reportType, ReportDefinitionDateRangeType dateRangeType, String schema) {
_rootSession = rootSession;
_reportType = reportType;
_dateRangeType = dateRangeType;
_columnNames = schemaToColumnNames(schema);
log.info("Downloaded fields are: " + Arrays.toString(_columnNames.toArray()));
long lowWatermark = state.getWorkunit().getLowWatermark(LongWatermark.class).getValue();
_startDate = dateFormatter.print(watermarkFormatter.parseDateTime(Long.toString(lowWatermark)));
_endDate = _startDate;
_dailyPartition = state.getPropAsBoolean(GoogleAdWordsSource.KEY_CUSTOM_DATE_DAILY, false);
_debugFileOutputPath = state.getProp(GoogleAdWordsSource.KEY_DEBUG_PATH_FILE, "");
_debugStringOutputPath = state.getProp(GoogleAdWordsSource.KEY_DEBUG_PATH_STRING, "");
_skipReportHeader = state.getPropAsBoolean(GoogleAdWordsSource.KEY_REPORTING_SKIP_REPORT_HEADER, true);
_skipColumnHeader = state.getPropAsBoolean(GoogleAdWordsSource.KEY_REPORTING_SKIP_COLUMN_HEADER, true);
_skipReportSummary = state.getPropAsBoolean(GoogleAdWordsSource.KEY_REPORTING_SKIP_REPORT_SUMMARY, true);
_useRawEnumValues = state.getPropAsBoolean(GoogleAdWordsSource.KEY_REPORTING_USE_RAW_ENUM_VALUES, false);
_includeZeroImpressions = state.getPropAsBoolean(GoogleAdWordsSource.KEY_REPORTING_INCLUDE_ZERO_IMPRESSION, false);
}
static List<String> schemaToColumnNames(String schemaString) {
JsonArray schemaArray = new JsonParser().parse(schemaString).getAsJsonArray();
List<String> fields = new ArrayList<>();
for (int i = 0; i < schemaArray.size(); i++) {
fields.add(schemaArray.get(i).getAsJsonObject().get("columnName").getAsString());
}
return fields;
}
public void downloadAllReports(Collection<String> accounts, final LinkedBlockingDeque<String[]> reportRows)
throws InterruptedException {
ExecutorService threadPool = Executors.newFixedThreadPool(Math.min(8, accounts.size()));
List<Pair<String, String>> dates = getDates();
Map<String, Future<Void>> jobs = new HashMap<>();
for (String acc : accounts) {
final String account = acc;
for (Pair<String, String> dateRange : dates) {
final Pair<String, String> range = dateRange;
final String jobName;
if (_dateRangeType.equals(ReportDefinitionDateRangeType.ALL_TIME)) {
jobName = String.format("'all-time report for %s'", account);
} else {
jobName = String.format("'report for %s from %s to %s'", account, range.getLeft(), range.getRight());
}
Future<Void> job = threadPool.submit(new Callable<Void>() {
@Override
public Void call()
throws ReportDownloadResponseException, InterruptedException, IOException, ReportException {
log.info("Start downloading " + jobName);
ExponentialBackOff backOff = backOffBuilder.build();
int numberOfAttempts = 0;
while (true) {
++numberOfAttempts;
try {
downloadReport(account, range.getLeft(), range.getRight(), reportRows);
log.info("Successfully downloaded " + jobName);
return null;
} catch (ReportException e) {
long sleepMillis = backOff.nextBackOffMillis();
log.info("Downloading %s failed #%d try: %s. Will sleep for %d milliseconds.", jobName,
numberOfAttempts, e.getMessage(), sleepMillis);
if (sleepMillis == BackOff.STOP) {
throw new ReportException(String
.format("Downloading %s failed after maximum elapsed millis: %d", jobName,
backOff.getMaxElapsedTimeMillis()), e);
}
Thread.sleep(sleepMillis);
}
}
}
});
jobs.put(jobName, job);
Thread.sleep(100);
}
}
threadPool.shutdown();
//Collect all failed jobs.
Map<String, Exception> failedJobs = new HashMap<>();
for (Map.Entry<String, Future<Void>> job : jobs.entrySet()) {
try {
job.getValue().get();
} catch (Exception e) {
failedJobs.put(job.getKey(), e);
}
}
if (!failedJobs.isEmpty()) {
log.error(String.format("%d downloading jobs failed: ", failedJobs.size()));
for (Map.Entry<String, Exception> fail : failedJobs.entrySet()) {
log.error(String.format("%s => %s", fail.getKey(), fail.getValue().getMessage()));
}
}
log.info("End of downloading all reports.");
}
/**
* @param account the account of the report you want to download
* @param startDate start date for custom_date range type
* @param endDate end date for custom_date range type
* @param reportRows the sink that accumulates all downloaded rows
* @throws ReportDownloadResponseException This is not retryable
* @throws ReportException ReportException represents a potentially retryable error
*/
private void downloadReport(String account, String startDate, String endDate,
LinkedBlockingDeque<String[]> reportRows)
throws ReportDownloadResponseException, ReportException, InterruptedException, IOException {
Selector selector = new Selector();
selector.getFields().addAll(_columnNames);
String reportName;
if (_dateRangeType.equals(ReportDefinitionDateRangeType.CUSTOM_DATE)) {
DateRange value = new DateRange();
value.setMin(startDate);
value.setMax(endDate);
selector.setDateRange(value);
reportName = String.format("%s_%s/%s_%s.csv", startDate, endDate, _reportType.toString(), account);
} else {
reportName = String.format("all_time/%s_%s.csv", _reportType.toString(), account);
}
ReportDefinition reportDef = new ReportDefinition();
reportDef.setReportName(reportName);
reportDef.setDateRangeType(_dateRangeType);
reportDef.setReportType(_reportType);
reportDef.setDownloadFormat(DownloadFormat.GZIPPED_CSV);
reportDef.setSelector(selector);
//API defaults all configurations to false
ReportingConfiguration reportConfig =
new ReportingConfiguration.Builder().skipReportHeader(_skipReportHeader).skipColumnHeader(_skipColumnHeader)
.skipReportSummary(_skipReportSummary)
.useRawEnumValues(_useRawEnumValues) //return enum field values as enum values instead of display values
.includeZeroImpressions(_includeZeroImpressions).build();
AdWordsSession.ImmutableAdWordsSession session;
try {
session = _rootSession.newBuilder().withClientCustomerId(account).withReportingConfiguration(reportConfig)
.buildImmutable();
} catch (ValidationException e) {
throw new RuntimeException(e);
}
ReportDownloader downloader = new ReportDownloader(session);
ReportDownloadResponse response = downloader.downloadReport(reportDef);
InputStream zippedStream = response.getInputStream();
if (zippedStream == null) {
log.warn("Got empty stream for " + reportName);
return;
}
if (!_debugFileOutputPath.trim().isEmpty()) {
//FILE mode debug will not save output to GOBBLIN_WORK_DIR
File debugFile = new File(_debugFileOutputPath, reportName);
createPath(debugFile);
writeZippedStreamToFile(zippedStream, debugFile);
return;
}
FileWriter debugFileWriter = null;
try {
if (!_debugStringOutputPath.trim().isEmpty()) {
//if STRING mode debug is enabled. A copy of downloaded strings/reports will be saved.
File debugFile = new File(_debugStringOutputPath, reportName);
createPath(debugFile);
debugFileWriter = new FileWriter(debugFile);
}
processResponse(zippedStream, reportRows, debugFileWriter);
} catch (IOException e) {
throw new RuntimeException(
String.format("Failed unzipping and processing records for %s. Reason is: %s", reportName, e.getMessage()),
e);
} finally {
if (debugFileWriter != null) {
debugFileWriter.close();
}
}
}
private static void createPath(File file) {
//Clean up file if exists
if (file.exists()) {
boolean delete = file.delete();
if (!delete) {
throw new RuntimeException(String.format("Cannot delete debug file: %s", file));
}
}
boolean created = new File(file.getParent()).mkdirs();
if (!created) {
throw new RuntimeException(String.format("Cannot create debug file: %s", file));
}
}
private static GZIPInputStream processResponse(InputStream zippedStream, LinkedBlockingDeque<String[]> reportRows,
FileWriter debugFw)
throws IOException, InterruptedException {
byte[] buffer = new byte[SIZE];
try (GZIPInputStream gzipInputStream = new GZIPInputStream(zippedStream)) {
String partiallyConsumed = "";
while (true) {
int c = gzipInputStream.read(buffer, 0, SIZE);
if (c == -1) {
break; //end of stream
}
if (c == 0) {
continue; //read empty, continue reading
}
String str = new String(buffer, 0, c, "UTF-8"); //"c" can very likely be less than SIZE.
if (debugFw != null) {
debugFw.write(str); //save a copy if STRING mode debug is enabled
}
partiallyConsumed = addToQueue(reportRows, partiallyConsumed, str);
}
return gzipInputStream;
}
}
/**
* Concatenate previously partially consumed string with current read, then try to split the whole string.
* A whole record will be added to reportRows(data sink).
* The last partially consumed string, if exists, will be returned to be processed in next round.
*/
static String addToQueue(LinkedBlockingDeque<String[]> reportRows, String previous, String current)
throws InterruptedException, IOException {
int start = -1;
int i = -1;
int len = current.length();
while (++i < len) {
if (current.charAt(i) != '\n') {
continue;
}
String row;
if (start < 0) {
row = previous + current.substring(0, i);
} else {
row = current.substring(start, i);
}
String[] splits = splitter.parseLine(row);
String[] transformed = new String[splits.length];
for (int s = 0; s < splits.length; ++s) {
String trimmed = splits[s].trim();
if (trimmed.equals("
transformed[s] = null;
} else {
transformed[s] = trimmed;
}
}
reportRows.put(transformed);
start = i + 1;
}
if (start < 0) {
return previous + current;
}
return current.substring(start);
}
private void writeZippedStreamToFile(InputStream zippedStream, File reportFile)
throws IOException {
byte[] buffer = new byte[SIZE];
int c;
try (GZIPInputStream gzipInputStream = new GZIPInputStream(zippedStream);
OutputStream unzipped = new FileOutputStream(reportFile)) {
while ((c = gzipInputStream.read(buffer, 0, SIZE)) >= 0) {
unzipped.write(buffer, 0, c);
}
}
}
public List<Pair<String, String>> getDates() {
if (_dateRangeType.equals(ReportDefinitionDateRangeType.ALL_TIME)) {
return Arrays.asList(Pair.of("", ""));
} else {
DateTimeFormatter dateFormatter = DateTimeFormat.forPattern("yyyyMMdd");
if (_dailyPartition) {
DateTime start = dateFormatter.parseDateTime(_startDate);
DateTime end = dateFormatter.parseDateTime(_endDate);
List<Pair<String, String>> ret = new ArrayList<>();
while (start.compareTo(end) <= 0) {
ret.add(Pair.of(dateFormatter.print(start), dateFormatter.print(start)));
start = start.plusDays(1);
}
return ret;
} else {
return Arrays.asList(Pair.of(_startDate, _endDate));
}
}
}
}
|
package org.dbflute.erflute.editor.model.diagram_contents.element.node.table;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;
import org.dbflute.erflute.core.util.Format;
import org.dbflute.erflute.db.DBManager;
import org.dbflute.erflute.db.DBManagerFactory;
import org.dbflute.erflute.editor.model.ObjectModel;
import org.dbflute.erflute.editor.model.diagram_contents.element.connection.Relationship;
import org.dbflute.erflute.editor.model.diagram_contents.element.connection.WalkerConnection;
import org.dbflute.erflute.editor.model.diagram_contents.element.node.DiagramWalker;
import org.dbflute.erflute.editor.model.diagram_contents.element.node.Location;
import org.dbflute.erflute.editor.model.diagram_contents.element.node.table.column.ColumnHolder;
import org.dbflute.erflute.editor.model.diagram_contents.element.node.table.column.CopyColumn;
import org.dbflute.erflute.editor.model.diagram_contents.element.node.table.column.ERColumn;
import org.dbflute.erflute.editor.model.diagram_contents.element.node.table.column.NormalColumn;
import org.dbflute.erflute.editor.model.diagram_contents.element.node.table.properties.TableViewProperties;
import org.dbflute.erflute.editor.model.diagram_contents.not_element.dictionary.CopyWord;
import org.dbflute.erflute.editor.model.diagram_contents.not_element.dictionary.Dictionary;
import org.dbflute.erflute.editor.model.diagram_contents.not_element.dictionary.Word;
import org.dbflute.erflute.editor.model.diagram_contents.not_element.group.ColumnGroup;
public abstract class TableView extends DiagramWalker implements ObjectModel, ColumnHolder, Comparable<TableView> {
// Definition
private static final long serialVersionUID = 1L;
public static final String PROPERTY_CHANGE_PHYSICAL_NAME = "table_view_physicalName";
public static final String PROPERTY_CHANGE_LOGICAL_NAME = "table_view_logicalName";
public static final String PROPERTY_CHANGE_COLUMNS = "columns";
public static final int DEFAULT_WIDTH = 120;
public static final int DEFAULT_HEIGHT = 75;
public static final Comparator<TableView> PHYSICAL_NAME_COMPARATOR = new TableViewPhysicalNameComparator();
public static final Comparator<TableView> LOGICAL_NAME_COMPARATOR = new TableViewLogicalNameComparator();
// Attribute
private String physicalName;
private String logicalName;
private String description;
protected List<ERColumn> columns;
protected TableViewProperties tableViewProperties;
// Constructor
public TableView() {
this.columns = new ArrayList<>();
}
// Location
@Override
public void setLocation(Location location) {
super.setLocation(location);
if (this.getDiagram() != null) {
for (final Relationship relationship : getOutgoingRelationshipList()) {
relationship.setParentMove();
}
for (final Relationship relation : getIncomingRelationshipList()) {
relation.setParentMove();
}
}
}
// Column
public List<NormalColumn> getNormalColumns() {
final List<NormalColumn> normalColumns = new ArrayList<>();
for (final ERColumn column : columns) {
if (column instanceof NormalColumn) {
normalColumns.add((NormalColumn) column);
}
}
return normalColumns;
}
public List<NormalColumn> getExpandedColumns() {
final List<NormalColumn> expandedColumns = new ArrayList<>();
for (final ERColumn column : this.getColumns()) {
if (column instanceof NormalColumn) {
final NormalColumn normalColumn = (NormalColumn) column;
expandedColumns.add(normalColumn);
} else if (column instanceof ColumnGroup) {
final ColumnGroup groupColumn = (ColumnGroup) column;
expandedColumns.addAll(groupColumn.getColumns());
}
}
return expandedColumns;
}
public void setDirty() {
this.firePropertyChange(PROPERTY_CHANGE_COLUMNS, null, null);
}
public void addColumn(ERColumn column) {
this.getColumns().add(column);
column.setColumnHolder(this);
this.firePropertyChange(PROPERTY_CHANGE_COLUMNS, null, null);
}
public void addColumn(int index, ERColumn column) {
this.getColumns().add(index, column);
column.setColumnHolder(this);
this.firePropertyChange(PROPERTY_CHANGE_COLUMNS, null, null);
}
public void removeColumn(ERColumn column) {
this.columns.remove(column);
this.firePropertyChange(PROPERTY_CHANGE_COLUMNS, null, null);
}
public NormalColumn findColumnByPhysicalName(String physicalName) {
final List<NormalColumn> normalColumns = getNormalColumns();
for (final NormalColumn normalColumn : normalColumns) {
if (physicalName.equalsIgnoreCase(normalColumn.getPhysicalName())) {
return normalColumn;
}
}
return null;
}
// Copy
public TableView copyTableViewData(TableView to) {
to.setDiagram(getDiagram());
to.setPhysicalName(getPhysicalName());
to.setLogicalName(getLogicalName());
to.setDescription(getDescription());
final List<ERColumn> columns = new ArrayList<>();
for (final ERColumn fromColumn : getColumns()) {
if (fromColumn instanceof NormalColumn) {
final NormalColumn normalColumn = (NormalColumn) fromColumn;
final NormalColumn copyColumn = new CopyColumn(normalColumn);
if (normalColumn.getWord() != null) {
copyColumn.setWord(new CopyWord(normalColumn.getWord()));
}
columns.add(copyColumn);
} else {
columns.add(fromColumn);
}
}
to.setColumns(columns);
to.setOutgoing(getOutgoings());
to.setIncoming(getIncomings());
return to;
}
public abstract TableView copyData();
// Restructure
public void restructureData(TableView to) {
final Dictionary dictionary = this.getDiagram().getDiagramContents().getDictionary();
to.setPhysicalName(this.getPhysicalName());
to.setLogicalName(this.getLogicalName());
to.setDescription(this.getDescription());
if (getColor() != null) {
to.setColor(this.getColor()[0], this.getColor()[1], this.getColor()[2]);
}
for (final NormalColumn toColumn : to.getNormalColumns()) {
dictionary.remove(toColumn);
}
final List<ERColumn> columns = new ArrayList<>();
final List<NormalColumn> newPrimaryKeyColumns = new ArrayList<>();
for (final ERColumn fromColumn : getColumns()) {
if (columns.stream().anyMatch(c -> c.same(fromColumn))) {
continue;
}
if (fromColumn instanceof NormalColumn) {
final CopyColumn copyColumn = (CopyColumn) fromColumn;
CopyWord copyWord = copyColumn.getWord();
if (copyColumn.isForeignKey()) {
copyWord = null;
}
if (copyWord != null) {
final Word originalWord = copyColumn.getOriginalWord();
dictionary.copyTo(copyWord, originalWord);
}
final NormalColumn restructuredColumn = copyColumn.getRestructuredColumn();
restructuredColumn.setColumnHolder(this);
if (copyWord == null) {
restructuredColumn.setWord(null);
}
columns.add(restructuredColumn);
if (restructuredColumn.isPrimaryKey()) {
newPrimaryKeyColumns.add(restructuredColumn);
}
dictionary.add(restructuredColumn);
} else {
columns.add(fromColumn);
}
}
this.setTargetTableRelation(to, newPrimaryKeyColumns);
to.setColumns(columns);
}
// Relationship
private void setTargetTableRelation(TableView sourceTable, List<NormalColumn> newPrimaryKeyColumns) {
for (final Relationship relationship : sourceTable.getOutgoingRelationshipList()) {
if (relationship.isReferenceForPK()) {
final TableView targetTable = relationship.getTargetTableView();
final List<NormalColumn> foreignKeyColumns = relationship.getForeignKeyColumns();
boolean isPrimary = true;
boolean isPrimaryChanged = false;
for (final NormalColumn primaryKeyColumn : newPrimaryKeyColumns) {
boolean isReferenced = false;
for (final Iterator<NormalColumn> iter = foreignKeyColumns.iterator(); iter.hasNext();) {
final NormalColumn foreignKeyColumn = iter.next();
if (isPrimary) {
isPrimary = foreignKeyColumn.isPrimaryKey();
}
for (final NormalColumn referencedColumn : foreignKeyColumn.getReferencedColumnList()) {
if (referencedColumn == primaryKeyColumn) {
isReferenced = true;
iter.remove();
break;
}
}
if (isReferenced) {
break;
}
}
if (!isReferenced) {
if (isPrimary) {
isPrimaryChanged = true;
}
final NormalColumn foreignKeyColumn = new NormalColumn(primaryKeyColumn, primaryKeyColumn, relationship, isPrimary);
targetTable.addColumn(foreignKeyColumn);
}
}
for (final NormalColumn removedColumn : foreignKeyColumns) {
if (removedColumn.isPrimaryKey()) {
isPrimaryChanged = true;
}
targetTable.removeColumn(removedColumn);
}
if (isPrimaryChanged) {
final List<NormalColumn> nextNewPrimaryKeyColumns = ((ERTable) targetTable).getPrimaryKeys();
this.setTargetTableRelation(targetTable, nextNewPrimaryKeyColumns);
}
targetTable.setDirty();
}
}
}
public List<Relationship> getIncomingRelationshipList() {
final List<Relationship> relations = new ArrayList<>();
for (final WalkerConnection connection : getIncomings()) {
if (connection instanceof Relationship) {
relations.add((Relationship) connection);
}
}
return relations;
}
public List<Relationship> getOutgoingRelationshipList() {
final List<Relationship> relations = new ArrayList<>();
for (final WalkerConnection connection : getOutgoings()) {
if (connection instanceof Relationship) {
relations.add((Relationship) connection);
}
}
Collections.sort(relations);
return relations;
}
// Column Group
public void replaceColumnGroup(ColumnGroup oldColumnGroup, ColumnGroup newColumnGroup) {
final int index = this.columns.indexOf(oldColumnGroup);
if (index != -1) {
this.columns.remove(index);
this.columns.add(index, newColumnGroup);
}
}
// Name with Schema
public String getNameWithSchema(String database) {
final StringBuilder sb = new StringBuilder();
final DBManager dbManager = DBManagerFactory.getDBManager(database);
if (!dbManager.isSupported(DBManager.SUPPORT_SCHEMA)) {
return Format.null2blank(this.getPhysicalName());
}
final TableViewProperties tableViewProperties = this.getDiagram().getDiagramContents().getSettings().getTableViewProperties();
String schema = this.tableViewProperties.getSchema();
if (schema == null || schema.equals("")) {
schema = tableViewProperties.getSchema();
}
if (schema != null && !schema.equals("")) {
sb.append(schema);
sb.append(".");
}
sb.append(this.getPhysicalName());
return sb.toString();
}
// TableView ID
public String buildTableViewId() {
return getIdPrefix() + "." + getPhysicalName();
}
protected abstract String getIdPrefix();
// Basic Override
@Override
public int compareTo(TableView other) {
return PHYSICAL_NAME_COMPARATOR.compare(this, other);
}
private static class TableViewPhysicalNameComparator implements Comparator<TableView> {
@Override
public int compare(TableView o1, TableView o2) {
if (o1 == o2) {
return 0;
}
if (o2 == null) {
return -1;
}
if (o1 == null) {
return 1;
}
final String schema1 = o1.getTableViewProperties().getSchema();
final String schema2 = o2.getTableViewProperties().getSchema();
final int compareTo = Format.null2blank(schema1).toUpperCase().compareTo(Format.null2blank(schema2).toUpperCase());
if (compareTo != 0) {
return compareTo;
}
int value = Format.null2blank(o1.physicalName).toUpperCase().compareTo(Format.null2blank(o2.physicalName).toUpperCase());
if (value != 0) {
return value;
}
value = Format.null2blank(o1.logicalName).toUpperCase().compareTo(Format.null2blank(o2.logicalName).toUpperCase());
if (value != 0) {
return value;
}
return 0;
}
}
private static class TableViewLogicalNameComparator implements Comparator<TableView> {
@Override
public int compare(TableView o1, TableView o2) {
if (o1 == o2) {
return 0;
}
if (o2 == null) {
return -1;
}
if (o1 == null) {
return 1;
}
final String schema1 = o1.getTableViewProperties().getSchema();
final String schema2 = o2.getTableViewProperties().getSchema();
final int compareTo = Format.null2blank(schema1).toUpperCase().compareTo(Format.null2blank(schema2).toUpperCase());
if (compareTo != 0) {
return compareTo;
}
int value = Format.null2blank(o1.logicalName).toUpperCase().compareTo(Format.null2blank(o2.logicalName).toUpperCase());
if (value != 0) {
return value;
}
value = Format.null2blank(o1.physicalName).toUpperCase().compareTo(Format.null2blank(o2.physicalName).toUpperCase());
if (value != 0) {
return value;
}
return 0;
}
}
@Override
public boolean isUsePersistentId() {
return false;
}
@Override
public boolean isIndenpendentOnModel() {
return false;
}
// Accessor
public String getPhysicalName() {
return physicalName;
}
public void setPhysicalName(String physicalName) {
final String old = this.physicalName;
this.physicalName = physicalName;
this.firePropertyChange(PROPERTY_CHANGE_PHYSICAL_NAME, old, physicalName);
}
public String getLogicalName() {
return logicalName;
}
public void setLogicalName(String logicalName) {
final String old = this.logicalName;
this.logicalName = logicalName;
this.firePropertyChange(PROPERTY_CHANGE_LOGICAL_NAME, old, logicalName);
}
@Override
public String getName() {
return this.getPhysicalName(); // #for_erflute change logical to physical for fixed sort
}
@Override
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public List<ERColumn> getColumns() {
return columns;
}
public ERColumn getColumn(int index) {
return this.columns.get(index);
}
public void setColumns(List<ERColumn> columns) {
this.columns = columns;
for (final ERColumn column : columns) {
column.setColumnHolder(this);
}
firePropertyChange(PROPERTY_CHANGE_COLUMNS, null, null);
}
public TableViewProperties getTableViewProperties() {
return tableViewProperties;
}
public void changeTableViewProperty(final TableView sourceTableView) {
sourceTableView.restructureData(this);
this.getDiagram().changeTable(sourceTableView);
this.getDiagram().doChangeTable(sourceTableView);
}
}
|
package ca.uhn.fhir.rest.server.interceptor.auth;
import ca.uhn.fhir.context.FhirContext;
import ca.uhn.fhir.context.api.AddProfileTagEnum;
import ca.uhn.fhir.interceptor.api.HookParams;
import ca.uhn.fhir.interceptor.api.IInterceptorBroadcaster;
import ca.uhn.fhir.interceptor.api.Pointcut;
import ca.uhn.fhir.model.primitive.IdDt;
import ca.uhn.fhir.rest.annotation.*;
import ca.uhn.fhir.rest.api.Constants;
import ca.uhn.fhir.rest.api.*;
import ca.uhn.fhir.rest.api.server.RequestDetails;
import ca.uhn.fhir.rest.param.ReferenceParam;
import ca.uhn.fhir.rest.param.TokenAndListParam;
import ca.uhn.fhir.rest.server.FifoMemoryPagingProvider;
import ca.uhn.fhir.rest.server.IResourceProvider;
import ca.uhn.fhir.rest.server.RestfulServer;
import ca.uhn.fhir.rest.server.exceptions.ResourceNotFoundException;
import ca.uhn.fhir.rest.server.interceptor.IServerInterceptor.ActionRequestDetails;
import ca.uhn.fhir.rest.server.servlet.ServletRequestDetails;
import ca.uhn.fhir.rest.server.tenant.UrlBaseTenantIdentificationStrategy;
import ca.uhn.fhir.test.utilities.JettyUtil;
import ca.uhn.fhir.util.TestUtil;
import ca.uhn.fhir.util.UrlUtil;
import com.google.common.base.Charsets;
import com.google.common.collect.Lists;
import org.apache.commons.io.IOUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.*;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.servlet.ServletHandler;
import org.eclipse.jetty.servlet.ServletHolder;
import org.hl7.fhir.instance.model.api.IBaseResource;
import org.hl7.fhir.instance.model.api.IIdType;
import org.hl7.fhir.r4.model.*;
import org.junit.*;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.TimeUnit;
import static org.apache.commons.lang3.StringUtils.isNotBlank;
import static org.hamcrest.Matchers.containsString;
import static org.junit.Assert.*;
public class AuthorizationInterceptorR4Test {
private static final String ERR403 = "{\"resourceType\":\"OperationOutcome\",\"issue\":[{\"severity\":\"error\",\"code\":\"processing\",\"diagnostics\":\"Access denied by default policy (no applicable rules)\"}]}";
private static final org.slf4j.Logger ourLog = org.slf4j.LoggerFactory.getLogger(AuthorizationInterceptorR4Test.class);
private static CloseableHttpClient ourClient;
private static String ourConditionalCreateId;
private static FhirContext ourCtx = FhirContext.forR4();
private static boolean ourHitMethod;
private static int ourPort;
private static List<Resource> ourReturn;
private static List<IBaseResource> ourDeleted;
private static Server ourServer;
private static RestfulServer ourServlet;
@Before
public void before() {
ourCtx.setAddProfileTagWhenEncoding(AddProfileTagEnum.NEVER);
ourServlet.getInterceptorService().unregisterAllInterceptors();
ourServlet.setTenantIdentificationStrategy(null);
ourReturn = null;
ourDeleted = null;
ourHitMethod = false;
ourConditionalCreateId = "1123";
}
private Resource createCarePlan(Integer theId, String theSubjectId) {
CarePlan retVal = new CarePlan();
if (theId != null) {
retVal.setId(new IdType("CarePlan", (long) theId));
}
retVal.setSubject(new Reference("Patient/" + theSubjectId));
return retVal;
}
private Resource createDiagnosticReport(Integer theId, String theSubjectId) {
DiagnosticReport retVal = new DiagnosticReport();
if (theId != null) {
retVal.setId(new IdType("DiagnosticReport", (long) theId));
}
retVal.getCode().setText("OBS");
retVal.setSubject(new Reference(theSubjectId));
return retVal;
}
private HttpEntity createFhirResourceEntity(IBaseResource theResource) {
String out = ourCtx.newJsonParser().encodeResourceToString(theResource);
return new StringEntity(out, ContentType.create(Constants.CT_FHIR_JSON, "UTF-8"));
}
private Resource createObservation(Integer theId, String theSubjectId) {
Observation retVal = new Observation();
if (theId != null) {
retVal.setId(new IdType("Observation", (long) theId));
}
retVal.getCode().setText("OBS");
retVal.setSubject(new Reference(theSubjectId));
if (theSubjectId != null && theSubjectId.startsWith("
Patient p = new Patient();
p.setId(theSubjectId);
p.setActive(true);
retVal.addContained(p);
}
return retVal;
}
private Organization createOrganization(int theIndex) {
Organization retVal = new Organization();
retVal.setId("" + theIndex);
retVal.setName("Org " + theIndex);
return retVal;
}
private Resource createPatient(Integer theId) {
Patient retVal = new Patient();
if (theId != null) {
retVal.setId(new IdType("Patient", (long) theId));
}
retVal.addName().setFamily("FAM");
return retVal;
}
private Resource createPatient(Integer theId, int theVersion) {
Resource retVal = createPatient(theId);
retVal.setId(retVal.getIdElement().withVersion(Integer.toString(theVersion)));
return retVal;
}
private Bundle createTransactionWithPlaceholdersRequestBundle() {
// Create a input that will be used as a transaction
Bundle input = new Bundle();
input.setType(Bundle.BundleType.TRANSACTION);
String encounterId = "123-123";
String encounterSystem = "http://our.internal.code.system/encounter";
Encounter encounter = new Encounter();
encounter.addIdentifier(new Identifier().setValue(encounterId)
.setSystem(encounterSystem));
encounter.setStatus(Encounter.EncounterStatus.FINISHED);
Patient p = new Patient()
.addIdentifier(new Identifier().setValue("321-321").setSystem("http://our.internal.code.system/patient"));
p.setId(IdDt.newRandomUuid());
// add patient to input so its created
input.addEntry()
.setFullUrl(p.getId())
.setResource(p)
.getRequest()
.setUrl("Patient")
.setMethod(Bundle.HTTPVerb.POST);
Reference patientRef = new Reference(p.getId());
encounter.setSubject(patientRef);
Condition condition = new Condition()
.setCode(new CodeableConcept().addCoding(
new Coding("http://hl7.org/fhir/icd-10", "S53.40", "FOREARM SPRAIN / STRAIN")))
.setSubject(patientRef);
condition.setId(IdDt.newRandomUuid());
// add condition to input so its created
input.addEntry()
.setFullUrl(condition.getId())
.setResource(condition)
.getRequest()
.setUrl("Condition")
.setMethod(Bundle.HTTPVerb.POST);
Encounter.DiagnosisComponent dc = new Encounter.DiagnosisComponent();
dc.setCondition(new Reference(condition.getId()));
encounter.addDiagnosis(dc);
CodeableConcept reason = new CodeableConcept();
reason.setText("SLIPPED ON FLOOR,PAIN L) ELBOW");
encounter.addReasonCode(reason);
// add encounter to input so its created
input.addEntry()
.setResource(encounter)
.getRequest()
.setUrl("Encounter")
.setIfNoneExist("identifier=" + encounterSystem + "|" + encounterId)
.setMethod(Bundle.HTTPVerb.POST);
return input;
}
private Bundle createTransactionWithPlaceholdersResponseBundle() {
Bundle output = new Bundle();
output.setType(Bundle.BundleType.TRANSACTIONRESPONSE);
output.addEntry()
.setResource(new Patient().setActive(true)) // don't give this an ID
.getResponse().setLocation("/Patient/1");
return output;
}
private String extractResponseAndClose(HttpResponse status) throws IOException {
if (status.getEntity() == null) {
return null;
}
String responseContent;
responseContent = IOUtils.toString(status.getEntity().getContent(), StandardCharsets.UTF_8);
IOUtils.closeQuietly(status.getEntity().getContent());
return responseContent;
}
@Test
public void testAllowAll() throws Exception {
ourServlet.registerInterceptor(new AuthorizationInterceptor(PolicyEnum.DENY) {
@Override
public List<IAuthRule> buildRuleList(RequestDetails theRequestDetails) {
return new RuleBuilder()
.deny("Rule 1").read().resourcesOfType(Patient.class).withAnyId().andThen()
.allowAll("Default Rule")
.build();
}
});
HttpGet httpGet;
HttpResponse status;
String response;
ourHitMethod = false;
ourReturn = Collections.singletonList(createObservation(10, "Patient/2"));
httpGet = new HttpGet("http://localhost:" + ourPort + "/Observation/10");
status = ourClient.execute(httpGet);
extractResponseAndClose(status);
assertEquals(200, status.getStatusLine().getStatusCode());
assertTrue(ourHitMethod);
ourHitMethod = false;
ourReturn = Collections.singletonList(createPatient(2));
httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient/1");
status = ourClient.execute(httpGet);
response = extractResponseAndClose(status);
ourLog.info(response);
assertThat(response, containsString("Access denied by rule: Rule 1"));
assertEquals(403, status.getStatusLine().getStatusCode());
assertFalse(ourHitMethod);
ourHitMethod = false;
httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient/1/$validate");
status = ourClient.execute(httpGet);
extractResponseAndClose(status);
assertEquals(200, status.getStatusLine().getStatusCode());
assertTrue(ourHitMethod);
}
@Test
public void testAllowAllForTenant() throws Exception {
ourServlet.setTenantIdentificationStrategy(new UrlBaseTenantIdentificationStrategy());
ourServlet.registerInterceptor(new AuthorizationInterceptor(PolicyEnum.DENY) {
@Override
public List<IAuthRule> buildRuleList(RequestDetails theRequestDetails) {
return new RuleBuilder()
.deny("Rule 1").read().resourcesOfType(Patient.class).withAnyId().forTenantIds("TENANTA").andThen()
.allowAll("Default Rule")
.build();
}
});
HttpGet httpGet;
HttpResponse status;
String response;
ourHitMethod = false;
ourReturn = Collections.singletonList(createObservation(10, "Patient/2"));
httpGet = new HttpGet("http://localhost:" + ourPort + "/TENANTA/Observation/10");
status = ourClient.execute(httpGet);
extractResponseAndClose(status);
assertEquals(200, status.getStatusLine().getStatusCode());
assertTrue(ourHitMethod);
ourHitMethod = false;
ourReturn = Collections.singletonList(createPatient(2));
httpGet = new HttpGet("http://localhost:" + ourPort + "/TENANTA/Patient/1");
status = ourClient.execute(httpGet);
response = extractResponseAndClose(status);
ourLog.info(response);
assertThat(response, containsString("Access denied by rule: Rule 1"));
assertEquals(403, status.getStatusLine().getStatusCode());
assertFalse(ourHitMethod);
ourHitMethod = false;
httpGet = new HttpGet("http://localhost:" + ourPort + "/TENANTA/Patient/1/$validate");
status = ourClient.execute(httpGet);
extractResponseAndClose(status);
assertEquals(200, status.getStatusLine().getStatusCode());
assertTrue(ourHitMethod);
}
@Test
public void testAllowByCompartmentUsingUnqualifiedIds() throws Exception {
ourServlet.registerInterceptor(new AuthorizationInterceptor(PolicyEnum.DENY) {
@Override
public List<IAuthRule> buildRuleList(RequestDetails theRequestDetails) {
return new RuleBuilder().allow().read().resourcesOfType(CarePlan.class).inCompartment("Patient", new IdType("Patient/123")).andThen().denyAll()
.build();
}
});
HttpGet httpGet;
HttpResponse status;
Patient patient;
CarePlan carePlan;
// Unqualified
patient = new Patient();
patient.setId("123");
carePlan = new CarePlan();
carePlan.setStatus(CarePlan.CarePlanStatus.ACTIVE);
carePlan.getSubject().setResource(patient);
ourHitMethod = false;
ourReturn = Collections.singletonList(carePlan);
httpGet = new HttpGet("http://localhost:" + ourPort + "/CarePlan/135154");
status = ourClient.execute(httpGet);
extractResponseAndClose(status);
assertEquals(200, status.getStatusLine().getStatusCode());
assertTrue(ourHitMethod);
// Qualified
patient = new Patient();
patient.setId("Patient/123");
carePlan = new CarePlan();
carePlan.setStatus(CarePlan.CarePlanStatus.ACTIVE);
carePlan.getSubject().setResource(patient);
ourHitMethod = false;
ourReturn = Collections.singletonList(carePlan);
httpGet = new HttpGet("http://localhost:" + ourPort + "/CarePlan/135154");
status = ourClient.execute(httpGet);
extractResponseAndClose(status);
assertEquals(200, status.getStatusLine().getStatusCode());
assertTrue(ourHitMethod);
// Wrong one
patient = new Patient();
patient.setId("456");
carePlan = new CarePlan();
carePlan.setStatus(CarePlan.CarePlanStatus.ACTIVE);
carePlan.getSubject().setResource(patient);
ourHitMethod = false;
ourReturn = Collections.singletonList(carePlan);
httpGet = new HttpGet("http://localhost:" + ourPort + "/CarePlan/135154");
status = ourClient.execute(httpGet);
extractResponseAndClose(status);
assertEquals(403, status.getStatusLine().getStatusCode());
assertTrue(ourHitMethod);
}
/**
* #528
*/
@Test
public void testAllowByCompartmentWithAnyType() throws Exception {
ourServlet.registerInterceptor(new AuthorizationInterceptor(PolicyEnum.DENY) {
@Override
public List<IAuthRule> buildRuleList(RequestDetails theRequestDetails) {
return new RuleBuilder()
.allow("Rule 1").read().allResources().inCompartment("Patient", new IdType("Patient/845bd9f1-3635-4866-a6c8-1ca085df5c1a"))
.andThen().denyAll()
.build();
}
});
HttpGet httpGet;
HttpResponse status;
ourHitMethod = false;
ourReturn = Collections.singletonList(createCarePlan(10, "845bd9f1-3635-4866-a6c8-1ca085df5c1a"));
httpGet = new HttpGet("http://localhost:" + ourPort + "/CarePlan/135154");
status = ourClient.execute(httpGet);
extractResponseAndClose(status);
assertEquals(200, status.getStatusLine().getStatusCode());
assertTrue(ourHitMethod);
ourHitMethod = false;
ourReturn = Collections.singletonList(createCarePlan(10, "FOO"));
httpGet = new HttpGet("http://localhost:" + ourPort + "/CarePlan/135154");
status = ourClient.execute(httpGet);
extractResponseAndClose(status);
assertEquals(403, status.getStatusLine().getStatusCode());
assertTrue(ourHitMethod);
}
@Test
public void testAllowByCompartmentWithAnyTypeWithTenantId() throws Exception {
ourServlet.setTenantIdentificationStrategy(new UrlBaseTenantIdentificationStrategy());
ourServlet.registerInterceptor(new AuthorizationInterceptor(PolicyEnum.DENY) {
@Override
public List<IAuthRule> buildRuleList(RequestDetails theRequestDetails) {
return new RuleBuilder()
.allow("Rule 1").read().allResources().inCompartment("Patient", new IdType("Patient/845bd9f1-3635-4866-a6c8-1ca085df5c1a")).forTenantIds("TENANTA")
.andThen().denyAll()
.build();
}
});
HttpGet httpGet;
HttpResponse status;
ourHitMethod = false;
ourReturn = Collections.singletonList(createCarePlan(10, "845bd9f1-3635-4866-a6c8-1ca085df5c1a"));
httpGet = new HttpGet("http://localhost:" + ourPort + "/TENANTA/CarePlan/135154");
status = ourClient.execute(httpGet);
extractResponseAndClose(status);
assertEquals(200, status.getStatusLine().getStatusCode());
assertTrue(ourHitMethod);
ourHitMethod = false;
ourReturn = Collections.singletonList(createCarePlan(10, "FOO"));
httpGet = new HttpGet("http://localhost:" + ourPort + "/TENANTA/CarePlan/135154");
status = ourClient.execute(httpGet);
extractResponseAndClose(status);
assertEquals(403, status.getStatusLine().getStatusCode());
assertTrue(ourHitMethod);
}
/**
* #528
*/
@Test
public void testAllowByCompartmentWithType() throws Exception {
ourServlet.registerInterceptor(new AuthorizationInterceptor(PolicyEnum.DENY) {
@Override
public List<IAuthRule> buildRuleList(RequestDetails theRequestDetails) {
return new RuleBuilder().allow("Rule 1").read().resourcesOfType(CarePlan.class).inCompartment("Patient", new IdType("Patient/845bd9f1-3635-4866-a6c8-1ca085df5c1a")).andThen().denyAll()
.build();
}
});
HttpGet httpGet;
HttpResponse status;
ourHitMethod = false;
ourReturn = Collections.singletonList(createCarePlan(10, "845bd9f1-3635-4866-a6c8-1ca085df5c1a"));
httpGet = new HttpGet("http://localhost:" + ourPort + "/CarePlan/135154");
status = ourClient.execute(httpGet);
extractResponseAndClose(status);
assertEquals(200, status.getStatusLine().getStatusCode());
assertTrue(ourHitMethod);
ourHitMethod = false;
ourReturn = Collections.singletonList(createCarePlan(10, "FOO"));
httpGet = new HttpGet("http://localhost:" + ourPort + "/CarePlan/135154");
status = ourClient.execute(httpGet);
extractResponseAndClose(status);
assertEquals(403, status.getStatusLine().getStatusCode());
assertTrue(ourHitMethod);
}
@Test
public void testBatchWhenOnlyTransactionAllowed() throws Exception {
ourServlet.registerInterceptor(new AuthorizationInterceptor(PolicyEnum.DENY) {
@Override
public List<IAuthRule> buildRuleList(RequestDetails theRequestDetails) {
return new RuleBuilder()
.allow("Rule 1").transaction().withAnyOperation().andApplyNormalRules().andThen()
.allow("Rule 2").write().allResources().inCompartment("Patient", new IdType("Patient/1")).andThen()
.allow("Rule 2").read().allResources().inCompartment("Patient", new IdType("Patient/1")).andThen()
.build();
}
});
Bundle input = new Bundle();
input.setType(Bundle.BundleType.BATCH);
input.addEntry().setResource(createPatient(1)).getRequest().setUrl("/Patient").setMethod(Bundle.HTTPVerb.POST);
Bundle output = new Bundle();
output.setType(Bundle.BundleType.TRANSACTIONRESPONSE);
output.addEntry().getResponse().setLocation("/Patient/1");
HttpPost httpPost;
HttpResponse status;
ourReturn = Collections.singletonList(output);
ourHitMethod = false;
httpPost = new HttpPost("http://localhost:" + ourPort + "/");
httpPost.setEntity(createFhirResourceEntity(input));
status = ourClient.execute(httpPost);
extractResponseAndClose(status);
assertEquals(200, status.getStatusLine().getStatusCode());
}
@Test
public void testBatchWhenTransactionReadDenied() throws Exception {
ourServlet.registerInterceptor(new AuthorizationInterceptor(PolicyEnum.DENY) {
@Override
public List<IAuthRule> buildRuleList(RequestDetails theRequestDetails) {
return new RuleBuilder()
.allow("Rule 1").transaction().withAnyOperation().andApplyNormalRules().andThen()
.allow("Rule 2").write().allResources().inCompartment("Patient", new IdType("Patient/1")).andThen()
.allow("Rule 2").read().allResources().inCompartment("Patient", new IdType("Patient/1")).andThen()
.build();
}
});
Bundle input = new Bundle();
input.setType(Bundle.BundleType.BATCH);
input.addEntry().setResource(createPatient(1)).getRequest().setUrl("/Patient").setMethod(Bundle.HTTPVerb.POST);
Bundle output = new Bundle();
output.setType(Bundle.BundleType.TRANSACTIONRESPONSE);
output.addEntry().setResource(createPatient(2));
HttpPost httpPost;
HttpResponse status;
ourReturn = Collections.singletonList(output);
ourHitMethod = false;
httpPost = new HttpPost("http://localhost:" + ourPort + "/");
httpPost.setEntity(createFhirResourceEntity(input));
status = ourClient.execute(httpPost);
extractResponseAndClose(status);
assertEquals(403, status.getStatusLine().getStatusCode());
}
@Test
public void testBatchWhenTransactionWrongBundleType() throws Exception {
ourServlet.registerInterceptor(new AuthorizationInterceptor(PolicyEnum.DENY) {
@Override
public List<IAuthRule> buildRuleList(RequestDetails theRequestDetails) {
return new RuleBuilder()
.allow("Rule 1").transaction().withAnyOperation().andApplyNormalRules().andThen()
.allow("Rule 2").write().allResources().inCompartment("Patient", new IdType("Patient/1")).andThen()
.allow("Rule 2").read().allResources().inCompartment("Patient", new IdType("Patient/1")).andThen()
.build();
}
});
Bundle input = new Bundle();
input.setType(Bundle.BundleType.COLLECTION);
input.addEntry().setResource(createPatient(1)).getRequest().setUrl("/Patient").setMethod(Bundle.HTTPVerb.POST);
Bundle output = new Bundle();
output.setType(Bundle.BundleType.TRANSACTIONRESPONSE);
output.addEntry().setResource(createPatient(1));
HttpPost httpPost;
HttpResponse status;
String response;
ourReturn = Collections.singletonList(output);
ourHitMethod = false;
httpPost = new HttpPost("http://localhost:" + ourPort + "/");
httpPost.setEntity(createFhirResourceEntity(input));
status = ourClient.execute(httpPost);
response = extractResponseAndClose(status);
assertEquals(422, status.getStatusLine().getStatusCode());
}
@Test
public void testDeleteByCompartment() throws Exception {
ourServlet.registerInterceptor(new AuthorizationInterceptor(PolicyEnum.DENY) {
@Override
public List<IAuthRule> buildRuleList(RequestDetails theRequestDetails) {
return new RuleBuilder()
.allow("Rule 1").delete().resourcesOfType(Patient.class).inCompartment("Patient", new IdType("Patient/1")).andThen()
.allow("Rule 2").delete().resourcesOfType(Observation.class).inCompartment("Patient", new IdType("Patient/1"))
.build();
}
});
HttpDelete httpDelete;
HttpResponse status;
ourHitMethod = false;
ourReturn = Collections.singletonList(createPatient(2));
httpDelete = new HttpDelete("http://localhost:" + ourPort + "/Patient/2");
status = ourClient.execute(httpDelete);
extractResponseAndClose(status);
assertEquals(403, status.getStatusLine().getStatusCode());
assertTrue(ourHitMethod);
ourHitMethod = false;
ourReturn = Collections.singletonList(createPatient(1));
httpDelete = new HttpDelete("http://localhost:" + ourPort + "/Patient/1");
status = ourClient.execute(httpDelete);
extractResponseAndClose(status);
assertEquals(204, status.getStatusLine().getStatusCode());
assertTrue(ourHitMethod);
}
@Test
public void testDeleteByCompartmentUsingTransaction() throws Exception {
ourServlet.registerInterceptor(new AuthorizationInterceptor(PolicyEnum.DENY) {
@Override
public List<IAuthRule> buildRuleList(RequestDetails theRequestDetails) {
return new RuleBuilder()
.allow("Rule 1").delete().resourcesOfType(Patient.class).inCompartment("Patient", new IdType("Patient/1")).andThen()
.allow("Rule 2").delete().resourcesOfType(Observation.class).inCompartment("Patient", new IdType("Patient/1")).andThen()
.allow().transaction().withAnyOperation().andApplyNormalRules().andThen()
.build();
}
});
HttpPost httpPost;
HttpResponse status;
String responseString;
Bundle responseBundle = new Bundle();
responseBundle.setType(Bundle.BundleType.TRANSACTIONRESPONSE);
Bundle bundle = new Bundle();
bundle.setType(Bundle.BundleType.TRANSACTION);
ourHitMethod = false;
bundle.getEntry().clear();
ourReturn = Collections.singletonList(responseBundle);
ourDeleted = Collections.singletonList(createPatient(2));
bundle.addEntry().getRequest().setMethod(Bundle.HTTPVerb.DELETE).setUrl("Patient/2");
httpPost = new HttpPost("http://localhost:" + ourPort + "/");
httpPost.setEntity(new StringEntity(ourCtx.newJsonParser().encodeResourceToString(bundle), ContentType.create(Constants.CT_FHIR_JSON_NEW, Charsets.UTF_8)));
status = ourClient.execute(httpPost);
responseString = extractResponseAndClose(status);
assertEquals(responseString, 403, status.getStatusLine().getStatusCode());
assertTrue(ourHitMethod);
ourHitMethod = false;
bundle.getEntry().clear();
bundle.addEntry().getRequest().setMethod(Bundle.HTTPVerb.DELETE).setUrl("Patient/1");
ourReturn = Collections.singletonList(responseBundle);
ourDeleted = Collections.singletonList(createPatient(1));
httpPost = new HttpPost("http://localhost:" + ourPort + "/");
httpPost.setEntity(new StringEntity(ourCtx.newJsonParser().encodeResourceToString(bundle), ContentType.create(Constants.CT_FHIR_JSON_NEW, Charsets.UTF_8)));
status = ourClient.execute(httpPost);
responseString = extractResponseAndClose(status);
assertEquals(responseString, 200, status.getStatusLine().getStatusCode());
assertTrue(ourHitMethod);
ourHitMethod = false;
bundle.getEntry().clear();
bundle.addEntry().getRequest().setMethod(Bundle.HTTPVerb.DELETE).setUrl("Observation?subject=Patient/2");
ourReturn = Collections.singletonList(responseBundle);
ourDeleted = Collections.singletonList(createObservation(99, "Patient/2"));
httpPost = new HttpPost("http://localhost:" + ourPort + "/");
httpPost.setEntity(new StringEntity(ourCtx.newJsonParser().encodeResourceToString(bundle), ContentType.create(Constants.CT_FHIR_JSON_NEW, Charsets.UTF_8)));
status = ourClient.execute(httpPost);
responseString = extractResponseAndClose(status);
assertEquals(responseString, 403, status.getStatusLine().getStatusCode());
assertTrue(ourHitMethod);
ourHitMethod = false;
bundle.getEntry().clear();
bundle.addEntry().getRequest().setMethod(Bundle.HTTPVerb.DELETE).setUrl("Observation?subject=Patient/1");
ourReturn = Collections.singletonList(responseBundle);
ourDeleted = Collections.singletonList(createObservation(99, "Patient/1"));
httpPost = new HttpPost("http://localhost:" + ourPort + "/");
httpPost.setEntity(new StringEntity(ourCtx.newJsonParser().encodeResourceToString(bundle), ContentType.create(Constants.CT_FHIR_JSON_NEW, Charsets.UTF_8)));
status = ourClient.execute(httpPost);
responseString = extractResponseAndClose(status);
assertEquals(responseString, 200, status.getStatusLine().getStatusCode());
assertTrue(ourHitMethod);
}
@Test
public void testDeleteByType() throws Exception {
ourServlet.registerInterceptor(new AuthorizationInterceptor(PolicyEnum.DENY) {
@Override
public List<IAuthRule> buildRuleList(RequestDetails theRequestDetails) {
return new RuleBuilder()
.allow("Rule 1").delete().resourcesOfType(Patient.class).withAnyId().andThen()
.build();
}
});
HttpDelete httpDelete;
HttpResponse status;
String responseString;
ourHitMethod = false;
ourReturn = Collections.singletonList(createPatient(2));
httpDelete = new HttpDelete("http://localhost:" + ourPort + "/Patient/1");
status = ourClient.execute(httpDelete);
responseString = extractResponseAndClose(status);
assertEquals(responseString, 204, status.getStatusLine().getStatusCode());
assertTrue(ourHitMethod);
ourHitMethod = false;
ourReturn = Collections.singletonList(createPatient(2));
httpDelete = new HttpDelete("http://localhost:" + ourPort + "/Observation/1");
status = ourClient.execute(httpDelete);
responseString = extractResponseAndClose(status);
assertEquals(responseString, 403, status.getStatusLine().getStatusCode());
assertFalse(ourHitMethod);
}
/**
* #528
*/
@Test
public void testDenyActionsNotOnTenant() throws Exception {
ourServlet.setTenantIdentificationStrategy(new UrlBaseTenantIdentificationStrategy());
ourServlet.registerInterceptor(new AuthorizationInterceptor(PolicyEnum.ALLOW) {
@Override
public List<IAuthRule> buildRuleList(RequestDetails theRequestDetails) {
return new RuleBuilder().denyAll().notForTenantIds("TENANTA", "TENANTB").build();
}
});
HttpGet httpGet;
HttpResponse status;
String response;
ourReturn = Collections.singletonList(createPatient(2));
ourHitMethod = false;
httpGet = new HttpGet("http://localhost:" + ourPort + "/TENANTA/Patient/1");
status = ourClient.execute(httpGet);
extractResponseAndClose(status);
assertEquals(200, status.getStatusLine().getStatusCode());
assertTrue(ourHitMethod);
ourReturn = Collections.singletonList(createObservation(10, "Patient/2"));
ourHitMethod = false;
httpGet = new HttpGet("http://localhost:" + ourPort + "/TENANTC/Patient/1");
status = ourClient.execute(httpGet);
response = extractResponseAndClose(status);
ourLog.info(response);
assertThat(response, containsString("Access denied by rule: (unnamed rule)"));
assertEquals(403, status.getStatusLine().getStatusCode());
assertFalse(ourHitMethod);
}
@Test
public void testDenyAll() throws Exception {
ourServlet.registerInterceptor(new AuthorizationInterceptor(PolicyEnum.DENY) {
@Override
public List<IAuthRule> buildRuleList(RequestDetails theRequestDetails) {
return new RuleBuilder()
.allow().read().resourcesOfType(Patient.class).withAnyId().andThen()
.denyAll("Default Rule")
.build();
}
@Override
protected void handleDeny(Verdict decision) {
// Make sure the toString() method on Verdict never fails
ourLog.info("Denying with decision: {}", decision);
super.handleDeny(decision);
}
});
HttpGet httpGet;
HttpResponse status;
String response;
ourHitMethod = false;
ourReturn = Collections.singletonList(createPatient(2));
httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient/1");
status = ourClient.execute(httpGet);
extractResponseAndClose(status);
assertEquals(200, status.getStatusLine().getStatusCode());
assertTrue(ourHitMethod);
ourHitMethod = false;
ourReturn = Collections.singletonList(createObservation(10, "Patient/2"));
httpGet = new HttpGet("http://localhost:" + ourPort + "/Observation/10");
status = ourClient.execute(httpGet);
response = extractResponseAndClose(status);
ourLog.info(response);
assertThat(response, containsString("Access denied by rule: Default Rule"));
assertEquals(403, status.getStatusLine().getStatusCode());
assertFalse(ourHitMethod);
ourHitMethod = false;
httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient/1/$validate");
status = ourClient.execute(httpGet);
response = extractResponseAndClose(status);
ourLog.info(response);
assertThat(response, containsString("Access denied by rule: Default Rule"));
assertEquals(403, status.getStatusLine().getStatusCode());
assertFalse(ourHitMethod);
ourHitMethod = false;
httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient/1/$opName");
status = ourClient.execute(httpGet);
response = extractResponseAndClose(status);
ourLog.info(response);
assertThat(response, containsString("Access denied by rule: Default Rule"));
assertEquals(403, status.getStatusLine().getStatusCode());
assertFalse(ourHitMethod);
}
@Test
public void testDenyAllByDefault() throws Exception {
ourServlet.registerInterceptor(new AuthorizationInterceptor(PolicyEnum.DENY) {
@Override
public List<IAuthRule> buildRuleList(RequestDetails theRequestDetails) {
return new RuleBuilder()
.allow().read().resourcesOfType(Patient.class).withAnyId().andThen()
.build();
}
@Override
protected void handleDeny(Verdict decision) {
// Make sure the toString() method on Verdict never fails
ourLog.info("Denying with decision: {}", decision);
super.handleDeny(decision);
}
});
HttpGet httpGet;
HttpResponse status;
String response;
ourHitMethod = false;
ourReturn = Collections.singletonList(createPatient(2));
httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient/1");
status = ourClient.execute(httpGet);
extractResponseAndClose(status);
assertEquals(200, status.getStatusLine().getStatusCode());
assertTrue(ourHitMethod);
ourHitMethod = false;
ourReturn = Collections.singletonList(createObservation(10, "Patient/2"));
httpGet = new HttpGet("http://localhost:" + ourPort + "/Observation/10");
status = ourClient.execute(httpGet);
response = extractResponseAndClose(status);
ourLog.info(response);
assertThat(response, containsString("Access denied by default policy"));
assertEquals(403, status.getStatusLine().getStatusCode());
assertFalse(ourHitMethod);
ourHitMethod = false;
httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient/1/$validate");
status = ourClient.execute(httpGet);
response = extractResponseAndClose(status);
ourLog.info(response);
assertThat(response, containsString("Access denied by default policy"));
assertEquals(403, status.getStatusLine().getStatusCode());
assertFalse(ourHitMethod);
ourHitMethod = false;
httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient/1/$opName");
status = ourClient.execute(httpGet);
response = extractResponseAndClose(status);
ourLog.info(response);
assertThat(response, containsString("Access denied by default policy"));
assertEquals(403, status.getStatusLine().getStatusCode());
assertFalse(ourHitMethod);
}
/**
* #528
*/
@Test
public void testDenyByCompartmentWithAnyType() throws Exception {
ourServlet.registerInterceptor(new AuthorizationInterceptor(PolicyEnum.DENY) {
@Override
public List<IAuthRule> buildRuleList(RequestDetails theRequestDetails) {
return new RuleBuilder().deny("Rule 1").read().allResources().inCompartment("Patient", new IdType("Patient/845bd9f1-3635-4866-a6c8-1ca085df5c1a")).andThen().allowAll().build();
}
});
HttpGet httpGet;
HttpResponse status;
ourHitMethod = false;
ourReturn = Collections.singletonList(createCarePlan(10, "845bd9f1-3635-4866-a6c8-1ca085df5c1a"));
httpGet = new HttpGet("http://localhost:" + ourPort + "/CarePlan/135154");
status = ourClient.execute(httpGet);
extractResponseAndClose(status);
assertEquals(403, status.getStatusLine().getStatusCode());
assertTrue(ourHitMethod);
ourHitMethod = false;
ourReturn = Collections.singletonList(createCarePlan(10, "FOO"));
httpGet = new HttpGet("http://localhost:" + ourPort + "/CarePlan/135154");
status = ourClient.execute(httpGet);
extractResponseAndClose(status);
assertEquals(200, status.getStatusLine().getStatusCode());
assertTrue(ourHitMethod);
}
/**
* #528
*/
@Test
public void testDenyByCompartmentWithType() throws Exception {
ourServlet.registerInterceptor(new AuthorizationInterceptor(PolicyEnum.DENY) {
@Override
public List<IAuthRule> buildRuleList(RequestDetails theRequestDetails) {
return new RuleBuilder().deny("Rule 1").read().resourcesOfType(CarePlan.class).inCompartment("Patient", new IdType("Patient/845bd9f1-3635-4866-a6c8-1ca085df5c1a")).andThen().allowAll()
.build();
}
});
HttpGet httpGet;
HttpResponse status;
ourHitMethod = false;
ourReturn = Collections.singletonList(createCarePlan(10, "845bd9f1-3635-4866-a6c8-1ca085df5c1a"));
httpGet = new HttpGet("http://localhost:" + ourPort + "/CarePlan/135154");
status = ourClient.execute(httpGet);
extractResponseAndClose(status);
assertEquals(403, status.getStatusLine().getStatusCode());
assertTrue(ourHitMethod);
ourHitMethod = false;
ourReturn = Collections.singletonList(createCarePlan(10, "FOO"));
httpGet = new HttpGet("http://localhost:" + ourPort + "/CarePlan/135154");
status = ourClient.execute(httpGet);
extractResponseAndClose(status);
assertEquals(200, status.getStatusLine().getStatusCode());
assertTrue(ourHitMethod);
}
@Test
public void testHistoryWithReadAll() throws Exception {
ourServlet.registerInterceptor(new AuthorizationInterceptor(PolicyEnum.DENY) {
@Override
public List<IAuthRule> buildRuleList(RequestDetails theRequestDetails) {
return new RuleBuilder()
.allow("Rule 1").read().allResources().withAnyId()
.build();
}
});
HttpGet httpGet;
HttpResponse status;
ourReturn = Collections.singletonList(createPatient(2, 1));
ourHitMethod = false;
httpGet = new HttpGet("http://localhost:" + ourPort + "/_history");
status = ourClient.execute(httpGet);
extractResponseAndClose(status);
assertEquals(200, status.getStatusLine().getStatusCode());
assertTrue(ourHitMethod);
ourHitMethod = false;
httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient/_history");
status = ourClient.execute(httpGet);
extractResponseAndClose(status);
assertEquals(200, status.getStatusLine().getStatusCode());
assertTrue(ourHitMethod);
ourHitMethod = false;
httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient/1/_history");
status = ourClient.execute(httpGet);
extractResponseAndClose(status);
assertEquals(200, status.getStatusLine().getStatusCode());
assertTrue(ourHitMethod);
}
@Test
public void testInvalidInstanceIds() {
try {
new RuleBuilder().allow("Rule 1").write().instance((String) null);
fail();
} catch (NullPointerException e) {
assertEquals("theId must not be null or empty", e.getMessage());
}
try {
new RuleBuilder().allow("Rule 1").write().instance("");
fail();
} catch (IllegalArgumentException e) {
assertEquals("theId must not be null or empty", e.getMessage());
}
try {
new RuleBuilder().allow("Rule 1").write().instance("Observation/");
fail();
} catch (IllegalArgumentException e) {
assertEquals("theId must contain an ID part", e.getMessage());
}
try {
new RuleBuilder().allow("Rule 1").write().instance(new IdType());
fail();
} catch (NullPointerException e) {
assertEquals("theId.getValue() must not be null or empty", e.getMessage());
}
try {
new RuleBuilder().allow("Rule 1").write().instance(new IdType(""));
fail();
} catch (NullPointerException e) {
assertEquals("theId.getValue() must not be null or empty", e.getMessage());
}
try {
new RuleBuilder().allow("Rule 1").write().instance(new IdType("Observation", (String) null));
fail();
} catch (NullPointerException e) {
assertEquals("theId must contain an ID part", e.getMessage());
}
}
@Test
public void testMetadataAllow() throws Exception {
ourServlet.registerInterceptor(new AuthorizationInterceptor(PolicyEnum.DENY) {
@Override
public List<IAuthRule> buildRuleList(RequestDetails theRequestDetails) {
return new RuleBuilder()
.allow("Rule 1").metadata()
.build();
}
});
HttpGet httpGet;
HttpResponse status;
ourReturn = Collections.singletonList(createPatient(2));
ourHitMethod = false;
httpGet = new HttpGet("http://localhost:" + ourPort + "/metadata");
status = ourClient.execute(httpGet);
extractResponseAndClose(status);
assertEquals(200, status.getStatusLine().getStatusCode());
}
@Test
public void testMetadataDeny() throws Exception {
ourServlet.registerInterceptor(new AuthorizationInterceptor(PolicyEnum.ALLOW) {
@Override
public List<IAuthRule> buildRuleList(RequestDetails theRequestDetails) {
return new RuleBuilder()
.deny("Rule 1").metadata()
.build();
}
});
HttpGet httpGet;
HttpResponse status;
ourReturn = Collections.singletonList(createPatient(2));
ourHitMethod = false;
httpGet = new HttpGet("http://localhost:" + ourPort + "/metadata");
status = ourClient.execute(httpGet);
extractResponseAndClose(status);
assertEquals(403, status.getStatusLine().getStatusCode());
}
@Test
public void testOperationAnyName() throws Exception {
ourServlet.registerInterceptor(new AuthorizationInterceptor(PolicyEnum.DENY) {
@Override
public List<IAuthRule> buildRuleList(RequestDetails theRequestDetails) {
return new RuleBuilder()
.allow("RULE 1").operation().withAnyName().onServer().andRequireExplicitResponseAuthorization().andThen()
.build();
}
});
HttpGet httpGet;
HttpResponse status;
// Server
ourHitMethod = false;
ourReturn = Collections.singletonList(createObservation(10, "Patient/2"));
httpGet = new HttpGet("http://localhost:" + ourPort + "/$opName");
status = ourClient.execute(httpGet);
String response = extractResponseAndClose(status);
ourLog.info(response);
assertEquals(200, status.getStatusLine().getStatusCode());
assertTrue(ourHitMethod);
}
@Test
public void testOperationAppliesAtAnyLevel() throws Exception {
ourServlet.registerInterceptor(new AuthorizationInterceptor(PolicyEnum.DENY) {
@Override
public List<IAuthRule> buildRuleList(RequestDetails theRequestDetails) {
return new RuleBuilder()
.allow("RULE 1").operation().named("opName").atAnyLevel().andRequireExplicitResponseAuthorization().andThen()
.build();
}
});
HttpGet httpGet;
HttpResponse status;
String response;
// Server
ourHitMethod = false;
ourReturn = Collections.singletonList(createObservation(10, "Patient/2"));
httpGet = new HttpGet("http://localhost:" + ourPort + "/$opName");
status = ourClient.execute(httpGet);
response = extractResponseAndClose(status);
assertEquals(200, status.getStatusLine().getStatusCode());
assertTrue(ourHitMethod);
// Type
ourHitMethod = false;
ourReturn = Collections.singletonList(createPatient(2));
httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient/$opName");
status = ourClient.execute(httpGet);
response = extractResponseAndClose(status);
ourLog.info(response);
assertEquals(200, status.getStatusLine().getStatusCode());
assertTrue(ourHitMethod);
// Instance
ourHitMethod = false;
ourReturn = Collections.singletonList(createPatient(2));
httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient/1/$opName");
status = ourClient.execute(httpGet);
response = extractResponseAndClose(status);
ourLog.info(response);
assertEquals(200, status.getStatusLine().getStatusCode());
assertTrue(ourHitMethod);
// Instance Version
ourHitMethod = false;
ourReturn = Collections.singletonList(createPatient(2));
httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient/1/_history/2/$opName");
status = ourClient.execute(httpGet);
response = extractResponseAndClose(status);
ourLog.info(response);
assertEquals(200, status.getStatusLine().getStatusCode());
assertTrue(ourHitMethod);
}
@Test
public void testOperationAppliesAtAnyLevelWrongOpName() throws Exception {
ourServlet.registerInterceptor(new AuthorizationInterceptor(PolicyEnum.DENY) {
@Override
public List<IAuthRule> buildRuleList(RequestDetails theRequestDetails) {
return new RuleBuilder()
.allow("RULE 1").operation().named("opNameBadOp").atAnyLevel().andRequireExplicitResponseAuthorization().andThen()
.build();
}
});
HttpGet httpGet;
HttpResponse status;
String response;
// Server
ourHitMethod = false;
ourReturn = Collections.singletonList(createObservation(10, "Patient/2"));
httpGet = new HttpGet("http://localhost:" + ourPort + "/$opName");
status = ourClient.execute(httpGet);
response = extractResponseAndClose(status);
assertEquals(403, status.getStatusLine().getStatusCode());
assertFalse(ourHitMethod);
// Type
ourHitMethod = false;
ourReturn = Collections.singletonList(createPatient(2));
httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient/$opName");
status = ourClient.execute(httpGet);
response = extractResponseAndClose(status);
ourLog.info(response);
assertEquals(403, status.getStatusLine().getStatusCode());
assertFalse(ourHitMethod);
// Instance
ourHitMethod = false;
ourReturn = Collections.singletonList(createPatient(2));
httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient/1/$opName");
status = ourClient.execute(httpGet);
response = extractResponseAndClose(status);
ourLog.info(response);
assertEquals(403, status.getStatusLine().getStatusCode());
assertFalse(ourHitMethod);
// Instance Version
ourHitMethod = false;
ourReturn = Collections.singletonList(createPatient(2));
httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient/1/_history/2/$opName");
status = ourClient.execute(httpGet);
response = extractResponseAndClose(status);
ourLog.info(response);
assertEquals(403, status.getStatusLine().getStatusCode());
assertFalse(ourHitMethod);
}
@Test
public void testOperationByInstanceOfTypeAllowed() throws Exception {
ourServlet.registerInterceptor(new AuthorizationInterceptor(PolicyEnum.DENY) {
@Override
public List<IAuthRule> buildRuleList(RequestDetails theRequestDetails) {
return new RuleBuilder()
.allow("Rule 1").operation().named("everything").onInstancesOfType(Patient.class).andRequireExplicitResponseAuthorization()
.build();
}
});
HttpGet httpGet;
HttpResponse status;
String response;
ourReturn = new ArrayList<>();
ourHitMethod = false;
httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient/1/$everything");
status = ourClient.execute(httpGet);
response = extractResponseAndClose(status);
assertThat(response, containsString("Bundle"));
assertEquals(200, status.getStatusLine().getStatusCode());
assertEquals(true, ourHitMethod);
ourReturn = new ArrayList<>();
ourHitMethod = false;
httpGet = new HttpGet("http://localhost:" + ourPort + "/Encounter/1/$everything");
status = ourClient.execute(httpGet);
response = extractResponseAndClose(status);
assertThat(response, containsString("OperationOutcome"));
assertEquals(403, status.getStatusLine().getStatusCode());
assertEquals(false, ourHitMethod);
}
@Test
public void testOperationByInstanceOfTypeWithInvalidReturnValue() throws Exception {
ourServlet.registerInterceptor(new AuthorizationInterceptor(PolicyEnum.DENY) {
@Override
public List<IAuthRule> buildRuleList(RequestDetails theRequestDetails) {
return new RuleBuilder()
.allow("Rule 1").operation().named("everything").onInstancesOfType(Patient.class).andRequireExplicitResponseAuthorization().andThen()
.allow("Rule 2").read().allResources().inCompartment("Patient", new IdType("Patient/1")).andThen()
.build();
}
});
HttpGet httpGet;
HttpResponse status;
String response;
// With a return value we don't allow
ourReturn = Collections.singletonList(createPatient(222));
ourHitMethod = false;
httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient/1/$everything");
status = ourClient.execute(httpGet);
response = extractResponseAndClose(status);
assertThat(response, containsString("OperationOutcome"));
assertEquals(403, status.getStatusLine().getStatusCode());
assertEquals(true, ourHitMethod);
// With a return value we do
ourReturn = Collections.singletonList(createPatient(1));
ourHitMethod = false;
httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient/1/$everything");
status = ourClient.execute(httpGet);
response = extractResponseAndClose(status);
assertThat(response, containsString("Bundle"));
assertEquals(200, status.getStatusLine().getStatusCode());
assertEquals(true, ourHitMethod);
}
@Test
public void testOperationByInstanceOfTypeWithReturnValue() throws Exception {
ourServlet.registerInterceptor(new AuthorizationInterceptor(PolicyEnum.DENY) {
@Override
public List<IAuthRule> buildRuleList(RequestDetails theRequestDetails) {
return new RuleBuilder()
.allow("Rule 1").operation().named("everything").onInstancesOfType(Patient.class).andRequireExplicitResponseAuthorization()
.build();
}
});
HttpGet httpGet;
HttpResponse status;
String response;
ourReturn = new ArrayList<>();
ourHitMethod = false;
httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient/1/$everything");
status = ourClient.execute(httpGet);
response = extractResponseAndClose(status);
assertThat(response, containsString("Bundle"));
assertEquals(200, status.getStatusLine().getStatusCode());
assertEquals(true, ourHitMethod);
ourReturn = new ArrayList<>();
ourHitMethod = false;
httpGet = new HttpGet("http://localhost:" + ourPort + "/Encounter/1/$everything");
status = ourClient.execute(httpGet);
response = extractResponseAndClose(status);
assertThat(response, containsString("OperationOutcome"));
assertEquals(403, status.getStatusLine().getStatusCode());
assertEquals(false, ourHitMethod);
}
@Test
public void testOperationInstanceLevel() throws Exception {
ourServlet.registerInterceptor(new AuthorizationInterceptor(PolicyEnum.DENY) {
@Override
public List<IAuthRule> buildRuleList(RequestDetails theRequestDetails) {
return new RuleBuilder()
.allow("RULE 1").operation().named("opName").onInstance(new IdType("http://example.com/Patient/1/_history/2")).andRequireExplicitResponseAuthorization().andThen()
.build();
}
});
HttpGet httpGet;
HttpResponse status;
String response;
// Server
ourHitMethod = false;
ourReturn = Collections.singletonList(createObservation(10, "Patient/2"));
httpGet = new HttpGet("http://localhost:" + ourPort + "/$opName");
status = ourClient.execute(httpGet);
response = extractResponseAndClose(status);
assertThat(response, containsString("Access denied by default policy"));
assertEquals(403, status.getStatusLine().getStatusCode());
assertFalse(ourHitMethod);
// Type
ourHitMethod = false;
ourReturn = Collections.singletonList(createPatient(2));
httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient/$opName");
status = ourClient.execute(httpGet);
response = extractResponseAndClose(status);
ourLog.info(response);
assertThat(response, containsString("Access denied by default policy"));
assertEquals(403, status.getStatusLine().getStatusCode());
assertFalse(ourHitMethod);
// Instance
ourHitMethod = false;
ourReturn = Collections.singletonList(createPatient(2));
httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient/1/$opName");
status = ourClient.execute(httpGet);
response = extractResponseAndClose(status);
ourLog.info(response);
assertEquals(200, status.getStatusLine().getStatusCode());
assertTrue(ourHitMethod);
// Wrong instance
ourHitMethod = false;
ourReturn = Collections.singletonList(createPatient(2));
httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient/2/$opName");
status = ourClient.execute(httpGet);
response = extractResponseAndClose(status);
ourLog.info(response);
assertThat(response, containsString("Access denied by default policy"));
assertEquals(403, status.getStatusLine().getStatusCode());
assertFalse(ourHitMethod);
}
@Test
public void testOperationInstanceLevelAnyInstance() throws Exception {
ourServlet.registerInterceptor(new AuthorizationInterceptor(PolicyEnum.DENY) {
@Override
public List<IAuthRule> buildRuleList(RequestDetails theRequestDetails) {
return new RuleBuilder()
.allow("RULE 1").operation().named("opName").onAnyInstance().andRequireExplicitResponseAuthorization().andThen()
.build();
}
});
HttpGet httpGet;
HttpResponse status;
String response;
// Server
ourHitMethod = false;
ourReturn = Collections.singletonList(createObservation(10, "Patient/2"));
httpGet = new HttpGet("http://localhost:" + ourPort + "/$opName");
status = ourClient.execute(httpGet);
response = extractResponseAndClose(status);
assertThat(response, containsString("Access denied by default policy"));
assertEquals(403, status.getStatusLine().getStatusCode());
assertFalse(ourHitMethod);
// Type
ourHitMethod = false;
ourReturn = Collections.singletonList(createPatient(2));
httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient/$opName");
status = ourClient.execute(httpGet);
response = extractResponseAndClose(status);
ourLog.info(response);
assertThat(response, containsString("Access denied by default policy"));
assertEquals(403, status.getStatusLine().getStatusCode());
assertFalse(ourHitMethod);
// Instance
ourHitMethod = false;
ourReturn = Collections.singletonList(createPatient(2));
httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient/1/$opName");
status = ourClient.execute(httpGet);
response = extractResponseAndClose(status);
ourLog.info(response);
assertEquals(200, status.getStatusLine().getStatusCode());
assertTrue(ourHitMethod);
// Another Instance
ourHitMethod = false;
ourReturn = Collections.singletonList(createPatient(2));
httpGet = new HttpGet("http://localhost:" + ourPort + "/Observation/2/$opName");
status = ourClient.execute(httpGet);
response = extractResponseAndClose(status);
ourLog.info(response);
assertEquals(200, status.getStatusLine().getStatusCode());
assertTrue(ourHitMethod);
// Wrong name
ourHitMethod = false;
ourReturn = Collections.singletonList(createPatient(2));
httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient/2/$opName2");
status = ourClient.execute(httpGet);
response = extractResponseAndClose(status);
ourLog.info(response);
assertThat(response, containsString("Access denied by default policy"));
assertEquals(403, status.getStatusLine().getStatusCode());
assertFalse(ourHitMethod);
}
@Test
public void testOperationNotAllowedWithWritePermissiom() throws Exception {
ourServlet.registerInterceptor(new AuthorizationInterceptor(PolicyEnum.DENY) {
@Override
public List<IAuthRule> buildRuleList(RequestDetails theRequestDetails) {
return new RuleBuilder()
.allow("RULE 1").write().allResources().withAnyId().andThen()
.build();
}
});
HttpGet httpGet;
HttpResponse status;
String response;
// Server
ourHitMethod = false;
ourReturn = Collections.singletonList(createObservation(10, "Patient/2"));
httpGet = new HttpGet("http://localhost:" + ourPort + "/$opName");
status = ourClient.execute(httpGet);
response = extractResponseAndClose(status);
assertThat(response, containsString("Access denied by default policy"));
assertEquals(403, status.getStatusLine().getStatusCode());
assertFalse(ourHitMethod);
// System
ourHitMethod = false;
ourReturn = Collections.singletonList(createPatient(2));
httpGet = new HttpGet("http://localhost:" + ourPort + "/$opName");
status = ourClient.execute(httpGet);
response = extractResponseAndClose(status);
ourLog.info(response);
assertEquals(403, status.getStatusLine().getStatusCode());
assertFalse(ourHitMethod);
// Type
ourHitMethod = false;
ourReturn = Collections.singletonList(createPatient(2));
httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient/$opName");
status = ourClient.execute(httpGet);
response = extractResponseAndClose(status);
ourLog.info(response);
assertEquals(403, status.getStatusLine().getStatusCode());
assertFalse(ourHitMethod);
// Instance
ourHitMethod = false;
ourReturn = Collections.singletonList(createPatient(2));
httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient/123/$opName");
status = ourClient.execute(httpGet);
response = extractResponseAndClose(status);
ourLog.info(response);
assertEquals(403, status.getStatusLine().getStatusCode());
assertFalse(ourHitMethod);
}
@Test
public void testOperationServerLevel() throws Exception {
ourServlet.registerInterceptor(new AuthorizationInterceptor(PolicyEnum.DENY) {
@Override
public List<IAuthRule> buildRuleList(RequestDetails theRequestDetails) {
return new RuleBuilder()
.allow("RULE 1").operation().named("opName").onServer().andRequireExplicitResponseAuthorization().andThen()
.build();
}
});
HttpGet httpGet;
HttpResponse status;
String response;
// Server
ourHitMethod = false;
ourReturn = Collections.singletonList(createObservation(10, "Patient/2"));
httpGet = new HttpGet("http://localhost:" + ourPort + "/$opName");
status = ourClient.execute(httpGet);
extractResponseAndClose(status);
assertEquals(200, status.getStatusLine().getStatusCode());
assertTrue(ourHitMethod);
// Type
ourHitMethod = false;
ourReturn = Collections.singletonList(createPatient(2));
httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient/$opName");
status = ourClient.execute(httpGet);
response = extractResponseAndClose(status);
ourLog.info(response);
assertThat(response, containsString("Access denied by default policy"));
assertEquals(403, status.getStatusLine().getStatusCode());
assertFalse(ourHitMethod);
// Instance
ourHitMethod = false;
ourReturn = Collections.singletonList(createPatient(2));
httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient/1/$opName");
status = ourClient.execute(httpGet);
response = extractResponseAndClose(status);
ourLog.info(response);
assertThat(response, containsString("Access denied by default policy"));
assertEquals(403, status.getStatusLine().getStatusCode());
assertFalse(ourHitMethod);
}
@Test
public void testOperationTypeLevel() throws Exception {
ourServlet.registerInterceptor(new AuthorizationInterceptor(PolicyEnum.DENY) {
@Override
public List<IAuthRule> buildRuleList(RequestDetails theRequestDetails) {
return new RuleBuilder()
.allow("RULE 1").operation().named("opName").onType(Patient.class).andRequireExplicitResponseAuthorization().andThen()
.build();
}
});
HttpGet httpGet;
HttpResponse status;
String response;
// Server
ourHitMethod = false;
ourReturn = Collections.singletonList(createObservation(10, "Patient/2"));
httpGet = new HttpGet("http://localhost:" + ourPort + "/$opName");
status = ourClient.execute(httpGet);
response = extractResponseAndClose(status);
assertThat(response, containsString("Access denied by default policy"));
assertEquals(403, status.getStatusLine().getStatusCode());
assertFalse(ourHitMethod);
// Type
ourHitMethod = false;
ourReturn = Collections.singletonList(createPatient(2));
httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient/$opName");
status = ourClient.execute(httpGet);
response = extractResponseAndClose(status);
ourLog.info(response);
assertEquals(200, status.getStatusLine().getStatusCode());
assertTrue(ourHitMethod);
// Wrong type
ourHitMethod = false;
ourReturn = Collections.singletonList(createPatient(2));
httpGet = new HttpGet("http://localhost:" + ourPort + "/Observation/1/$opName");
status = ourClient.execute(httpGet);
response = extractResponseAndClose(status);
ourLog.info(response);
assertThat(response, containsString("Access denied by default policy"));
assertEquals(403, status.getStatusLine().getStatusCode());
assertFalse(ourHitMethod);
// Wrong name
ourHitMethod = false;
ourReturn = Collections.singletonList(createPatient(2));
httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient/1/$opName2");
status = ourClient.execute(httpGet);
response = extractResponseAndClose(status);
ourLog.info(response);
assertThat(response, containsString("Access denied by default policy"));
assertEquals(403, status.getStatusLine().getStatusCode());
assertFalse(ourHitMethod);
// Instance
ourHitMethod = false;
ourReturn = Collections.singletonList(createPatient(2));
httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient/1/$opName");
status = ourClient.execute(httpGet);
response = extractResponseAndClose(status);
ourLog.info(response);
assertThat(response, containsString("Access denied by default policy"));
assertEquals(403, status.getStatusLine().getStatusCode());
assertFalse(ourHitMethod);
}
@Test
public void testOperationTypeLevelWildcard() throws Exception {
ourServlet.registerInterceptor(new AuthorizationInterceptor(PolicyEnum.DENY) {
@Override
public List<IAuthRule> buildRuleList(RequestDetails theRequestDetails) {
return new RuleBuilder()
.allow("RULE 1").operation().named("opName").onAnyType().andRequireExplicitResponseAuthorization().andThen()
.build();
}
});
HttpGet httpGet;
HttpResponse status;
String response;
// Server
ourHitMethod = false;
ourReturn = Collections.singletonList(createObservation(10, "Patient/2"));
httpGet = new HttpGet("http://localhost:" + ourPort + "/$opName");
status = ourClient.execute(httpGet);
response = extractResponseAndClose(status);
assertThat(response, containsString("Access denied by default policy"));
assertEquals(403, status.getStatusLine().getStatusCode());
assertFalse(ourHitMethod);
// Type
ourHitMethod = false;
ourReturn = Collections.singletonList(createPatient(2));
httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient/$opName");
status = ourClient.execute(httpGet);
response = extractResponseAndClose(status);
ourLog.info(response);
assertEquals(200, status.getStatusLine().getStatusCode());
assertTrue(ourHitMethod);
// Another type
ourHitMethod = false;
ourReturn = Collections.singletonList(createPatient(2));
httpGet = new HttpGet("http://localhost:" + ourPort + "/Observation/$opName");
status = ourClient.execute(httpGet);
response = extractResponseAndClose(status);
ourLog.info(response);
assertEquals(200, status.getStatusLine().getStatusCode());
assertTrue(ourHitMethod);
// Wrong name
ourHitMethod = false;
ourReturn = Collections.singletonList(createPatient(2));
httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient/$opName2");
status = ourClient.execute(httpGet);
response = extractResponseAndClose(status);
ourLog.info(response);
assertThat(response, containsString("Access denied by default policy"));
assertEquals(403, status.getStatusLine().getStatusCode());
assertFalse(ourHitMethod);
// Instance
ourHitMethod = false;
ourReturn = Collections.singletonList(createPatient(2));
httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient/1/$opName");
status = ourClient.execute(httpGet);
response = extractResponseAndClose(status);
ourLog.info(response);
assertThat(response, containsString("Access denied by default policy"));
assertEquals(403, status.getStatusLine().getStatusCode());
assertFalse(ourHitMethod);
}
@Test
public void testOperationTypeLevelWithOperationMethodHavingOptionalIdParam() throws Exception {
ourServlet.registerInterceptor(new AuthorizationInterceptor(PolicyEnum.DENY) {
@Override
public List<IAuthRule> buildRuleList(RequestDetails theRequestDetails) {
return new RuleBuilder()
.allow("RULE 1").operation().named("opName").onType(Organization.class).andRequireExplicitResponseAuthorization().andThen()
.build();
}
});
HttpGet httpGet;
HttpResponse status;
String response;
// Server
ourHitMethod = false;
ourReturn = Collections.singletonList(createObservation(10, "Organization/2"));
httpGet = new HttpGet("http://localhost:" + ourPort + "/$opName");
status = ourClient.execute(httpGet);
response = extractResponseAndClose(status);
assertThat(response, containsString("Access denied by default policy"));
assertEquals(403, status.getStatusLine().getStatusCode());
assertFalse(ourHitMethod);
// Type
ourHitMethod = false;
ourReturn = Collections.singletonList(createOrganization(2));
httpGet = new HttpGet("http://localhost:" + ourPort + "/Organization/$opName");
status = ourClient.execute(httpGet);
response = extractResponseAndClose(status);
ourLog.info(response);
assertEquals(200, status.getStatusLine().getStatusCode());
assertTrue(ourHitMethod);
// Wrong type
ourHitMethod = false;
ourReturn = Collections.singletonList(createOrganization(2));
httpGet = new HttpGet("http://localhost:" + ourPort + "/Observation/1/$opName");
status = ourClient.execute(httpGet);
response = extractResponseAndClose(status);
ourLog.info(response);
assertThat(response, containsString("Access denied by default policy"));
assertEquals(403, status.getStatusLine().getStatusCode());
assertFalse(ourHitMethod);
// Instance
ourHitMethod = false;
ourReturn = Collections.singletonList(createOrganization(2));
httpGet = new HttpGet("http://localhost:" + ourPort + "/Organization/1/$opName");
status = ourClient.execute(httpGet);
response = extractResponseAndClose(status);
ourLog.info(response);
assertThat(response, containsString("Access denied by default policy"));
assertEquals(403, status.getStatusLine().getStatusCode());
assertFalse(ourHitMethod);
}
@Test
public void testOperationTypeLevelWithTenant() throws Exception {
ourServlet.setTenantIdentificationStrategy(new UrlBaseTenantIdentificationStrategy());
ourServlet.registerInterceptor(new AuthorizationInterceptor(PolicyEnum.DENY) {
@Override
public List<IAuthRule> buildRuleList(RequestDetails theRequestDetails) {
return new RuleBuilder()
.allow("RULE 1").operation().named("opName").onType(Patient.class).andRequireExplicitResponseAuthorization().forTenantIds("TENANTA").andThen()
.build();
}
});
HttpGet httpGet;
HttpResponse status;
String response;
// Right Tenant
ourHitMethod = false;
ourReturn = Collections.singletonList(createPatient(2));
httpGet = new HttpGet("http://localhost:" + ourPort + "/TENANTA/Patient/$opName");
status = ourClient.execute(httpGet);
response = extractResponseAndClose(status);
ourLog.info(response);
assertEquals(200, status.getStatusLine().getStatusCode());
assertTrue(ourHitMethod);
// Wrong Tenant
ourHitMethod = false;
ourReturn = Collections.singletonList(createObservation(10, "Patient/2"));
httpGet = new HttpGet("http://localhost:" + ourPort + "/TENANTC/Patient/$opName");
status = ourClient.execute(httpGet);
response = extractResponseAndClose(status);
assertThat(response, containsString("Access denied by default policy"));
assertEquals(403, status.getStatusLine().getStatusCode());
assertFalse(ourHitMethod);
}
@Test
public void testOperationTypeLevelDifferentBodyType() throws Exception {
ourServlet.registerInterceptor(new AuthorizationInterceptor(PolicyEnum.DENY) {
@Override
public List<IAuthRule> buildRuleList(RequestDetails theRequestDetails) {
return new RuleBuilder()
.allow("RULE 1").operation().named("process-message").onServer().andRequireExplicitResponseAuthorization().andThen()
.build();
}
});
HttpPost httpPost;
HttpResponse status;
String response;
Bundle input = new Bundle();
input.setType(Bundle.BundleType.MESSAGE);
String inputString = ourCtx.newJsonParser().encodeResourceToString(input);
// With body
ourHitMethod = false;
httpPost = new HttpPost("http://localhost:" + ourPort + "/$process-message");
httpPost.setEntity(new StringEntity(inputString, ContentType.create(Constants.CT_FHIR_JSON_NEW, Charsets.UTF_8)));
status = ourClient.execute(httpPost);
response = extractResponseAndClose(status);
ourLog.info(response);
assertEquals(200, status.getStatusLine().getStatusCode());
assertTrue(ourHitMethod);
// With body
ourHitMethod = false;
HttpGet httpGet = new HttpGet("http://localhost:" + ourPort + "/$process-message");
status = ourClient.execute(httpGet);
response = extractResponseAndClose(status);
ourLog.info(response);
assertEquals(200, status.getStatusLine().getStatusCode());
assertTrue(ourHitMethod);
}
@Test
public void testOperationWithTester() throws Exception {
ourServlet.registerInterceptor(new AuthorizationInterceptor(PolicyEnum.DENY) {
@Override
public List<IAuthRule> buildRuleList(RequestDetails theRequestDetails) {
return new RuleBuilder()
.allow("Rule 1").operation().named("everything").onInstancesOfType(Patient.class).andRequireExplicitResponseAuthorization().withTester(new IAuthRuleTester() {
@Override
public boolean matches(RestOperationTypeEnum theOperation, RequestDetails theRequestDetails, IIdType theInputResourceId, IBaseResource theInputResource) {
return theInputResourceId.getIdPart().equals("1");
}
})
.build();
}
});
HttpGet httpGet;
HttpResponse status;
String response;
ourReturn = new ArrayList<>();
ourHitMethod = false;
httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient/1/$everything");
status = ourClient.execute(httpGet);
response = extractResponseAndClose(status);
assertThat(response, containsString("Bundle"));
assertEquals(200, status.getStatusLine().getStatusCode());
assertEquals(true, ourHitMethod);
ourReturn = new ArrayList<>();
ourHitMethod = false;
httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient/2/$everything");
status = ourClient.execute(httpGet);
response = extractResponseAndClose(status);
assertThat(response, containsString("OperationOutcome"));
assertEquals(403, status.getStatusLine().getStatusCode());
assertEquals(false, ourHitMethod);
}
@Test
public void testPatchAllowed() throws IOException {
Observation obs = new Observation();
obs.setSubject(new Reference("Patient/999"));
ourServlet.registerInterceptor(new AuthorizationInterceptor(PolicyEnum.DENY) {
@Override
public List<IAuthRule> buildRuleList(RequestDetails theRequestDetails) {
return new RuleBuilder()
.allow().patch().allRequests().andThen()
.build();
}
});
String patchBody = "[\n" +
" { \"op\": \"replace\", \"path\": \"Observation/status\", \"value\": \"amended\" }\n" +
" ]";
HttpPatch patch = new HttpPatch("http://localhost:" + ourPort + "/Observation/123");
patch.setEntity(new StringEntity(patchBody, ContentType.create(Constants.CT_JSON_PATCH, Charsets.UTF_8)));
CloseableHttpResponse status = ourClient.execute(patch);
extractResponseAndClose(status);
assertEquals(200, status.getStatusLine().getStatusCode());
assertTrue(ourHitMethod);
}
@Test
public void testPatchNotAllowed() throws IOException {
Observation obs = new Observation();
obs.setSubject(new Reference("Patient/999"));
ourServlet.registerInterceptor(new AuthorizationInterceptor(PolicyEnum.DENY) {
@Override
public List<IAuthRule> buildRuleList(RequestDetails theRequestDetails) {
return new RuleBuilder()
.allow().metadata().andThen()
.build();
}
});
String patchBody = "[\n" +
" { \"op\": \"replace\", \"path\": \"Observation/status\", \"value\": \"amended\" }\n" +
" ]";
HttpPatch patch = new HttpPatch("http://localhost:" + ourPort + "/Observation/123");
patch.setEntity(new StringEntity(patchBody, ContentType.create(Constants.CT_JSON_PATCH, Charsets.UTF_8)));
CloseableHttpResponse status = ourClient.execute(patch);
extractResponseAndClose(status);
assertEquals(403, status.getStatusLine().getStatusCode());
assertFalse(ourHitMethod);
}
@Test
public void testGraphQLAllowed() throws Exception {
ourServlet.registerInterceptor(new AuthorizationInterceptor(PolicyEnum.DENY) {
@Override
public List<IAuthRule> buildRuleList(RequestDetails theRequestDetails) {
return new RuleBuilder()
.allow("Rule 1").graphQL().any().andThen()
.build();
}
});
HttpGet httpGet;
HttpResponse status;
String response;
ourReturn = Collections.singletonList(createPatient(2));
ourHitMethod = false;
httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient/1/$graphql?query=" + UrlUtil.escapeUrlParam("{name}"));
status = ourClient.execute(httpGet);
extractResponseAndClose(status);
assertEquals(200, status.getStatusLine().getStatusCode());
assertTrue(ourHitMethod);
}
@Test
public void testGraphQLDenied() throws Exception {
ourServlet.registerInterceptor(new AuthorizationInterceptor(PolicyEnum.DENY) {
@Override
public List<IAuthRule> buildRuleList(RequestDetails theRequestDetails) {
return new RuleBuilder()
.build();
}
});
HttpGet httpGet;
HttpResponse status;
String response;
ourReturn = Collections.singletonList(createPatient(2));
ourHitMethod = false;
httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient/1/$graphql?query=" + UrlUtil.escapeUrlParam("{name}"));
status = ourClient.execute(httpGet);
extractResponseAndClose(status);
assertEquals(403, status.getStatusLine().getStatusCode());
assertFalse(ourHitMethod);
}
@Test
public void testReadByAnyId() throws Exception {
ourServlet.registerInterceptor(new AuthorizationInterceptor(PolicyEnum.DENY) {
@Override
public List<IAuthRule> buildRuleList(RequestDetails theRequestDetails) {
return new RuleBuilder()
.allow("Rule 1").read().resourcesOfType(Patient.class).withAnyId()
.build();
}
});
HttpGet httpGet;
HttpResponse status;
String response;
ourReturn = Collections.singletonList(createPatient(2));
ourHitMethod = false;
httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient/1");
status = ourClient.execute(httpGet);
extractResponseAndClose(status);
assertEquals(200, status.getStatusLine().getStatusCode());
assertTrue(ourHitMethod);
ourReturn = Collections.singletonList(createPatient(2));
ourHitMethod = false;
httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient/1/_history/222");
status = ourClient.execute(httpGet);
extractResponseAndClose(status);
assertEquals(200, status.getStatusLine().getStatusCode());
assertTrue(ourHitMethod);
ourReturn = Collections.singletonList(createObservation(10, "Patient/2"));
ourHitMethod = false;
httpGet = new HttpGet("http://localhost:" + ourPort + "/Observation/10");
status = ourClient.execute(httpGet);
response = extractResponseAndClose(status);
ourLog.info(response);
assertThat(response, containsString("Access denied by default policy (no applicable rules)"));
assertEquals(403, status.getStatusLine().getStatusCode());
assertFalse(ourHitMethod);
ourReturn = Arrays.asList(createPatient(1), createObservation(10, "Patient/2"));
ourHitMethod = false;
httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient");
status = ourClient.execute(httpGet);
response = extractResponseAndClose(status);
ourLog.info(response);
assertThat(response, containsString("Access denied by default policy (no applicable rules)"));
assertEquals(403, status.getStatusLine().getStatusCode());
assertTrue(ourHitMethod);
ourReturn = Arrays.asList(createPatient(2), createObservation(10, "Patient/1"));
ourHitMethod = false;
httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient");
status = ourClient.execute(httpGet);
response = extractResponseAndClose(status);
ourLog.info(response);
assertThat(response, containsString("Access denied by default policy (no applicable rules)"));
assertEquals(403, status.getStatusLine().getStatusCode());
assertTrue(ourHitMethod);
}
@Test
public void testReadByAnyIdWithTenantId() throws Exception {
ourServlet.setTenantIdentificationStrategy(new UrlBaseTenantIdentificationStrategy());
ourServlet.registerInterceptor(new AuthorizationInterceptor(PolicyEnum.DENY) {
@Override
public List<IAuthRule> buildRuleList(RequestDetails theRequestDetails) {
return new RuleBuilder()
.allow("Rule 1").read().resourcesOfType(Patient.class).withAnyId().forTenantIds("TENANTA")
.build();
}
});
HttpGet httpGet;
HttpResponse status;
String response;
ourReturn = Collections.singletonList(createPatient(2));
ourHitMethod = false;
httpGet = new HttpGet("http://localhost:" + ourPort + "/TENANTA/Patient/1");
status = ourClient.execute(httpGet);
extractResponseAndClose(status);
assertEquals(200, status.getStatusLine().getStatusCode());
assertTrue(ourHitMethod);
ourReturn = Collections.singletonList(createPatient(2));
ourHitMethod = false;
httpGet = new HttpGet("http://localhost:" + ourPort + "/TENANTB/Patient/1");
status = ourClient.execute(httpGet);
response = extractResponseAndClose(status);
assertThat(response, containsString("Access denied by default policy (no applicable rules)"));
assertEquals(403, status.getStatusLine().getStatusCode());
assertFalse(ourHitMethod);
ourReturn = Collections.singletonList(createPatient(2));
ourHitMethod = false;
httpGet = new HttpGet("http://localhost:" + ourPort + "/TENANTA/Patient/1/_history/222");
status = ourClient.execute(httpGet);
extractResponseAndClose(status);
assertEquals(200, status.getStatusLine().getStatusCode());
assertTrue(ourHitMethod);
ourReturn = Collections.singletonList(createObservation(10, "Patient/2"));
ourHitMethod = false;
httpGet = new HttpGet("http://localhost:" + ourPort + "/TENANTA/Observation/10");
status = ourClient.execute(httpGet);
response = extractResponseAndClose(status);
ourLog.info(response);
assertThat(response, containsString("Access denied by default policy (no applicable rules)"));
assertEquals(403, status.getStatusLine().getStatusCode());
assertFalse(ourHitMethod);
ourReturn = Arrays.asList(createPatient(1), createObservation(10, "Patient/2"));
ourHitMethod = false;
httpGet = new HttpGet("http://localhost:" + ourPort + "/TENANTA/Patient");
status = ourClient.execute(httpGet);
response = extractResponseAndClose(status);
ourLog.info(response);
assertThat(response, containsString("Access denied by default policy (no applicable rules)"));
assertEquals(403, status.getStatusLine().getStatusCode());
assertTrue(ourHitMethod);
ourReturn = Arrays.asList(createPatient(2), createObservation(10, "Patient/1"));
ourHitMethod = false;
httpGet = new HttpGet("http://localhost:" + ourPort + "/TENANTA/Patient");
status = ourClient.execute(httpGet);
response = extractResponseAndClose(status);
ourLog.info(response);
assertThat(response, containsString("Access denied by default policy (no applicable rules)"));
assertEquals(403, status.getStatusLine().getStatusCode());
assertTrue(ourHitMethod);
}
@Test
public void testReadByAnyIdWithTester() throws Exception {
ourServlet.registerInterceptor(new AuthorizationInterceptor(PolicyEnum.DENY) {
@Override
public List<IAuthRule> buildRuleList(RequestDetails theRequestDetails) {
return new RuleBuilder()
.allow("Rule 1").read().resourcesOfType(Patient.class).withAnyId().withTester(new IAuthRuleTester() {
@Override
public boolean matches(RestOperationTypeEnum theOperation, RequestDetails theRequestDetails, IIdType theInputResourceId, IBaseResource theInputResource) {
return theInputResourceId != null && theInputResourceId.getIdPart().equals("1");
}
})
.build();
}
});
HttpGet httpGet;
HttpResponse status;
String response;
ourReturn = Collections.singletonList(createPatient(2));
ourHitMethod = false;
httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient/1");
status = ourClient.execute(httpGet);
extractResponseAndClose(status);
assertEquals(200, status.getStatusLine().getStatusCode());
assertTrue(ourHitMethod);
ourReturn = Collections.singletonList(createPatient(2));
ourHitMethod = false;
httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient/1/_history/222");
status = ourClient.execute(httpGet);
extractResponseAndClose(status);
assertEquals(200, status.getStatusLine().getStatusCode());
assertTrue(ourHitMethod);
ourReturn = Collections.singletonList(createObservation(10, "Patient/2"));
ourHitMethod = false;
httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient/10");
status = ourClient.execute(httpGet);
response = extractResponseAndClose(status);
ourLog.info(response);
assertThat(response, containsString("Access denied by default policy (no applicable rules)"));
assertEquals(403, status.getStatusLine().getStatusCode());
assertFalse(ourHitMethod);
ourReturn = Arrays.asList(createPatient(1), createObservation(10, "Patient/2"));
ourHitMethod = false;
httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient");
status = ourClient.execute(httpGet);
response = extractResponseAndClose(status);
ourLog.info(response);
assertThat(response, containsString("Access denied by default policy (no applicable rules)"));
assertEquals(403, status.getStatusLine().getStatusCode());
assertFalse(ourHitMethod);
}
@Test
public void testReadByCompartmentReadByIdParam() throws Exception {
ourServlet.registerInterceptor(new AuthorizationInterceptor(PolicyEnum.DENY) {
@Override
public List<IAuthRule> buildRuleList(RequestDetails theRequestDetails) {
return new RuleBuilder()
.allow("Rule 1").read().allResources().inCompartment("Patient", new IdType("Patient/1")).andThen()
.build();
}
});
HttpGet httpGet;
HttpResponse status;
ourReturn = Collections.singletonList(createPatient(1));
ourHitMethod = false;
httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient?_id=Patient/1");
status = ourClient.execute(httpGet);
extractResponseAndClose(status);
assertEquals(200, status.getStatusLine().getStatusCode());
assertTrue(ourHitMethod);
ourReturn = Collections.singletonList(createPatient(1));
ourHitMethod = false;
httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient?_id=1");
status = ourClient.execute(httpGet);
extractResponseAndClose(status);
assertEquals(200, status.getStatusLine().getStatusCode());
assertTrue(ourHitMethod);
ourHitMethod = false;
httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient?_id=Patient/2");
status = ourClient.execute(httpGet);
extractResponseAndClose(status);
assertEquals(403, status.getStatusLine().getStatusCode());
assertFalse(ourHitMethod);
}
@Test
public void testReadByCompartmentReadByPatientParam() throws Exception {
ourServlet.registerInterceptor(new AuthorizationInterceptor(PolicyEnum.DENY) {
@Override
public List<IAuthRule> buildRuleList(RequestDetails theRequestDetails) {
return new RuleBuilder()
.allow("Rule 1").read().allResources().inCompartment("Patient", new IdType("Patient/1")).andThen()
.build();
}
});
HttpGet httpGet;
HttpResponse status;
ourReturn = Collections.singletonList(createDiagnosticReport(1, "Patient/1"));
ourHitMethod = false;
httpGet = new HttpGet("http://localhost:" + ourPort + "/DiagnosticReport?patient=Patient/1");
status = ourClient.execute(httpGet);
extractResponseAndClose(status);
assertEquals(200, status.getStatusLine().getStatusCode());
assertTrue(ourHitMethod);
ourReturn = Collections.singletonList(createDiagnosticReport(1, "Patient/1"));
ourHitMethod = false;
httpGet = new HttpGet("http://localhost:" + ourPort + "/DiagnosticReport?patient=1");
status = ourClient.execute(httpGet);
extractResponseAndClose(status);
assertEquals(200, status.getStatusLine().getStatusCode());
assertTrue(ourHitMethod);
ourReturn = Collections.singletonList(createDiagnosticReport(1, "Patient/1"));
ourHitMethod = false;
httpGet = new HttpGet("http://localhost:" + ourPort + "/DiagnosticReport?patient=Patient/2");
status = ourClient.execute(httpGet);
extractResponseAndClose(status);
assertEquals(403, status.getStatusLine().getStatusCode());
assertFalse(ourHitMethod);
ourReturn = Collections.singletonList(createDiagnosticReport(1, "Patient/1"));
ourHitMethod = false;
httpGet = new HttpGet("http://localhost:" + ourPort + "/DiagnosticReport?subject=Patient/1");
status = ourClient.execute(httpGet);
extractResponseAndClose(status);
assertEquals(200, status.getStatusLine().getStatusCode());
assertTrue(ourHitMethod);
ourReturn = Collections.singletonList(createDiagnosticReport(1, "Patient/1"));
ourHitMethod = false;
httpGet = new HttpGet("http://localhost:" + ourPort + "/DiagnosticReport?subject=1");
status = ourClient.execute(httpGet);
extractResponseAndClose(status);
assertEquals(200, status.getStatusLine().getStatusCode());
assertTrue(ourHitMethod);
ourReturn = Collections.singletonList(createDiagnosticReport(1, "Patient/1"));
ourHitMethod = false;
httpGet = new HttpGet("http://localhost:" + ourPort + "/DiagnosticReport?subject=Patient/2");
status = ourClient.execute(httpGet);
extractResponseAndClose(status);
assertEquals(403, status.getStatusLine().getStatusCode());
assertFalse(ourHitMethod);
}
@Test
public void testReadByCompartmentRight() throws Exception {
ourServlet.registerInterceptor(new AuthorizationInterceptor(PolicyEnum.DENY) {
@Override
public List<IAuthRule> buildRuleList(RequestDetails theRequestDetails) {
return new RuleBuilder()
.allow("Rule 1").read().resourcesOfType(Patient.class).inCompartment("Patient", new IdType("Patient/1")).andThen()
.allow("Rule 2").read().resourcesOfType(Observation.class).inCompartment("Patient", new IdType("Patient/1"))
.build();
}
});
HttpGet httpGet;
HttpResponse status;
ourReturn = Collections.singletonList(createPatient(1));
ourHitMethod = false;
httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient/1");
status = ourClient.execute(httpGet);
extractResponseAndClose(status);
assertEquals(200, status.getStatusLine().getStatusCode());
assertTrue(ourHitMethod);
ourReturn = Collections.singletonList(createObservation(10, "Patient/1"));
ourHitMethod = false;
httpGet = new HttpGet("http://localhost:" + ourPort + "/Observation/10");
status = ourClient.execute(httpGet);
extractResponseAndClose(status);
assertEquals(200, status.getStatusLine().getStatusCode());
assertTrue(ourHitMethod);
ourReturn = Arrays.asList(createPatient(1), createObservation(10, "Patient/1"));
ourHitMethod = false;
httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient");
status = ourClient.execute(httpGet);
extractResponseAndClose(status);
assertEquals(403, status.getStatusLine().getStatusCode());
assertFalse(ourHitMethod);
}
@Test
public void testReadByCompartmentWrongAllTypesProactiveBlockEnabledNoResponse() throws Exception {
ourServlet.registerInterceptor(new AuthorizationInterceptor(PolicyEnum.DENY) {
@Override
public List<IAuthRule> buildRuleList(RequestDetails theRequestDetails) {
return new RuleBuilder()
.allow("Rule 1").read().allResources().inCompartment("Patient", new IdType("Patient/1")).andThen()
.build();
}
}.setFlags());
HttpGet httpGet;
HttpResponse status;
String response;
ourReturn = Collections.emptyList();
ourHitMethod = false;
httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient/2");
status = ourClient.execute(httpGet);
response = extractResponseAndClose(status);
ourLog.info(response);
assertEquals(403, status.getStatusLine().getStatusCode());
assertFalse(ourHitMethod);
ourHitMethod = false;
httpGet = new HttpGet("http://localhost:" + ourPort + "/Observation/10");
status = ourClient.execute(httpGet);
response = extractResponseAndClose(status);
ourLog.info(response);
assertEquals(404, status.getStatusLine().getStatusCode());
assertTrue(ourHitMethod);
ourHitMethod = false;
httpGet = new HttpGet("http://localhost:" + ourPort + "/CarePlan/10");
status = ourClient.execute(httpGet);
response = extractResponseAndClose(status);
ourLog.info(response);
assertEquals(404, status.getStatusLine().getStatusCode());
assertTrue(ourHitMethod);
ourHitMethod = false;
httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient");
status = ourClient.execute(httpGet);
response = extractResponseAndClose(status);
ourLog.info(response);
assertEquals(403, status.getStatusLine().getStatusCode());
assertFalse(ourHitMethod);
ourHitMethod = false;
httpGet = new HttpGet("http://localhost:" + ourPort + "/_history");
status = ourClient.execute(httpGet);
response = extractResponseAndClose(status);
ourLog.info(response);
assertEquals(403, status.getStatusLine().getStatusCode());
assertFalse(ourHitMethod);
ourHitMethod = false;
httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient/_history");
status = ourClient.execute(httpGet);
response = extractResponseAndClose(status);
ourLog.info(response);
assertEquals(403, status.getStatusLine().getStatusCode());
assertFalse(ourHitMethod);
ourHitMethod = false;
httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient/999/_history");
status = ourClient.execute(httpGet);
response = extractResponseAndClose(status);
ourLog.info(response);
assertEquals(403, status.getStatusLine().getStatusCode());
assertFalse(ourHitMethod);
}
@Test
public void testReadByCompartmentWrongProactiveBlockDisabled() throws Exception {
ourServlet.registerInterceptor(new AuthorizationInterceptor(PolicyEnum.DENY) {
@Override
public List<IAuthRule> buildRuleList(RequestDetails theRequestDetails) {
return new RuleBuilder()
.allow("Rule 1").read().resourcesOfType(Patient.class).inCompartment("Patient", new IdType("Patient/1")).andThen()
.allow("Rule 2").read().resourcesOfType(Observation.class).inCompartment("Patient", new IdType("Patient/1"))
.build();
}
}.setFlags(AuthorizationFlagsEnum.NO_NOT_PROACTIVELY_BLOCK_COMPARTMENT_READ_ACCESS));
HttpGet httpGet;
HttpResponse status;
String response;
ourReturn = Collections.singletonList(createPatient(2));
ourHitMethod = false;
httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient/2");
status = ourClient.execute(httpGet);
response = extractResponseAndClose(status);
ourLog.info(response);
assertThat(response, containsString("Access denied by default policy (no applicable rules)"));
assertEquals(403, status.getStatusLine().getStatusCode());
assertFalse(ourHitMethod);
ourReturn = Collections.singletonList(createObservation(10, "Patient/2"));
ourHitMethod = false;
httpGet = new HttpGet("http://localhost:" + ourPort + "/Observation/10");
status = ourClient.execute(httpGet);
response = extractResponseAndClose(status);
ourLog.info(response);
assertThat(response, containsString("Access denied by default policy (no applicable rules)"));
assertEquals(403, status.getStatusLine().getStatusCode());
assertTrue(ourHitMethod);
ourReturn = Collections.singletonList(createCarePlan(10, "Patient/2"));
ourHitMethod = false;
httpGet = new HttpGet("http://localhost:" + ourPort + "/CarePlan/10");
status = ourClient.execute(httpGet);
response = extractResponseAndClose(status);
ourLog.info(response);
assertThat(response, containsString("Access denied by default policy (no applicable rules)"));
assertEquals(403, status.getStatusLine().getStatusCode());
assertFalse(ourHitMethod);
ourReturn = Arrays.asList(createPatient(1), createObservation(10, "Patient/2"));
ourHitMethod = false;
httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient");
status = ourClient.execute(httpGet);
response = extractResponseAndClose(status);
ourLog.info(response);
assertThat(response, containsString("Access denied by default policy (no applicable rules)"));
assertEquals(403, status.getStatusLine().getStatusCode());
assertTrue(ourHitMethod);
ourReturn = Arrays.asList(createPatient(2), createObservation(10, "Patient/1"));
ourHitMethod = false;
httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient");
status = ourClient.execute(httpGet);
response = extractResponseAndClose(status);
ourLog.info(response);
assertThat(response, containsString("Access denied by default policy (no applicable rules)"));
assertEquals(403, status.getStatusLine().getStatusCode());
assertTrue(ourHitMethod);
}
@Test
public void testReadByCompartmentWrongProactiveBlockDisabledNoResponse() throws Exception {
ourServlet.registerInterceptor(new AuthorizationInterceptor(PolicyEnum.DENY) {
@Override
public List<IAuthRule> buildRuleList(RequestDetails theRequestDetails) {
return new RuleBuilder()
.allow("Rule 1").read().resourcesOfType(Patient.class).inCompartment("Patient", new IdType("Patient/1")).andThen()
.allow("Rule 2").read().resourcesOfType(Observation.class).inCompartment("Patient", new IdType("Patient/1"))
.build();
}
}.setFlags(AuthorizationFlagsEnum.NO_NOT_PROACTIVELY_BLOCK_COMPARTMENT_READ_ACCESS));
HttpGet httpGet;
HttpResponse status;
String response;
ourReturn = Collections.emptyList();
ourHitMethod = false;
httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient/2");
status = ourClient.execute(httpGet);
response = extractResponseAndClose(status);
ourLog.info(response);
assertEquals(403, status.getStatusLine().getStatusCode());
assertFalse(ourHitMethod);
ourHitMethod = false;
httpGet = new HttpGet("http://localhost:" + ourPort + "/Observation/10");
status = ourClient.execute(httpGet);
response = extractResponseAndClose(status);
ourLog.info(response);
assertEquals(404, status.getStatusLine().getStatusCode());
assertTrue(ourHitMethod);
ourHitMethod = false;
httpGet = new HttpGet("http://localhost:" + ourPort + "/CarePlan/10");
status = ourClient.execute(httpGet);
response = extractResponseAndClose(status);
ourLog.info(response);
assertEquals(403, status.getStatusLine().getStatusCode());
assertFalse(ourHitMethod);
ourHitMethod = false;
httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient");
status = ourClient.execute(httpGet);
response = extractResponseAndClose(status);
ourLog.info(response);
assertEquals(200, status.getStatusLine().getStatusCode());
assertTrue(ourHitMethod);
}
@Test
public void testReadByCompartmentWrongProactiveBlockEnabledNoResponse() throws Exception {
ourServlet.registerInterceptor(new AuthorizationInterceptor(PolicyEnum.DENY) {
@Override
public List<IAuthRule> buildRuleList(RequestDetails theRequestDetails) {
return new RuleBuilder()
.allow("Rule 1").read().resourcesOfType(Patient.class).inCompartment("Patient", new IdType("Patient/1")).andThen()
.allow("Rule 2").read().resourcesOfType(Observation.class).inCompartment("Patient", new IdType("Patient/1"))
.build();
}
}.setFlags());
HttpGet httpGet;
HttpResponse status;
String response;
ourReturn = Collections.emptyList();
ourHitMethod = false;
httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient/2");
status = ourClient.execute(httpGet);
response = extractResponseAndClose(status);
ourLog.info(response);
assertEquals(403, status.getStatusLine().getStatusCode());
assertFalse(ourHitMethod);
ourHitMethod = false;
httpGet = new HttpGet("http://localhost:" + ourPort + "/Observation/10");
status = ourClient.execute(httpGet);
response = extractResponseAndClose(status);
ourLog.info(response);
assertEquals(404, status.getStatusLine().getStatusCode());
assertTrue(ourHitMethod);
// CarePlan could potentially be in the Patient/1 compartment but we don't
// have any rules explicitly allowing CarePlan so it's blocked
ourHitMethod = false;
httpGet = new HttpGet("http://localhost:" + ourPort + "/CarePlan/10");
status = ourClient.execute(httpGet);
response = extractResponseAndClose(status);
ourLog.info(response);
assertEquals(403, status.getStatusLine().getStatusCode());
assertFalse(ourHitMethod);
ourHitMethod = false;
httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient");
status = ourClient.execute(httpGet);
response = extractResponseAndClose(status);
ourLog.info(response);
assertEquals(403, status.getStatusLine().getStatusCode());
assertFalse(ourHitMethod);
ourHitMethod = false;
httpGet = new HttpGet("http://localhost:" + ourPort + "/_history");
status = ourClient.execute(httpGet);
response = extractResponseAndClose(status);
ourLog.info(response);
assertEquals(403, status.getStatusLine().getStatusCode());
assertFalse(ourHitMethod);
ourHitMethod = false;
httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient/_history");
status = ourClient.execute(httpGet);
response = extractResponseAndClose(status);
ourLog.info(response);
assertEquals(403, status.getStatusLine().getStatusCode());
assertFalse(ourHitMethod);
ourHitMethod = false;
httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient/999/_history");
status = ourClient.execute(httpGet);
response = extractResponseAndClose(status);
ourLog.info(response);
assertEquals(403, status.getStatusLine().getStatusCode());
assertFalse(ourHitMethod);
}
@Test
public void testReadByCompartmentDoesntAllowContained() throws Exception {
ourServlet.registerInterceptor(new AuthorizationInterceptor(PolicyEnum.DENY) {
@Override
public List<IAuthRule> buildRuleList(RequestDetails theRequestDetails) {
return new RuleBuilder()
.allow("Rule 2").read().resourcesOfType(Observation.class).inCompartment("Patient", new IdType("Patient/1"))
.build();
}
}.setFlags());
HttpGet httpGet;
HttpResponse status;
String response;
// Read with allowed subject
ourReturn = Lists.newArrayList(createObservation(10, "Patient/1"));
ourHitMethod = false;
httpGet = new HttpGet("http://localhost:" + ourPort + "/Observation/10");
status = ourClient.execute(httpGet);
response = extractResponseAndClose(status);
ourLog.info(response);
assertEquals(200, status.getStatusLine().getStatusCode());
assertTrue(ourHitMethod);
// Read with contained
ourReturn = Lists.newArrayList(createObservation(10, "
ourHitMethod = false;
httpGet = new HttpGet("http://localhost:" + ourPort + "/Observation/10");
status = ourClient.execute(httpGet);
response = extractResponseAndClose(status);
ourLog.info(response);
assertEquals(403, status.getStatusLine().getStatusCode());
assertTrue(ourHitMethod);
// Read with contained
Observation obs = (Observation) createObservation(10, null);
obs.setSubject(new Reference(new Patient().setActive(true)));
ourReturn = Lists.newArrayList(obs);
ourHitMethod = false;
httpGet = new HttpGet("http://localhost:" + ourPort + "/Observation/10");
status = ourClient.execute(httpGet);
response = extractResponseAndClose(status);
ourLog.info(response);
assertEquals(403, status.getStatusLine().getStatusCode());
assertTrue(ourHitMethod);
}
@Test
public void testReadByInstance() throws Exception {
ourConditionalCreateId = "1";
ourServlet.registerInterceptor(new AuthorizationInterceptor(PolicyEnum.DENY) {
@Override
public List<IAuthRule> buildRuleList(RequestDetails theRequestDetails) {
return new RuleBuilder()
.allow("Rule 1").read().instance("Observation/900").andThen()
.allow("Rule 1").read().instance("901").andThen()
.build();
}
});
HttpResponse status;
String response;
HttpGet httpGet;
ourReturn = Collections.singletonList(createObservation(900, "Patient/1"));
ourHitMethod = false;
httpGet = new HttpGet("http://localhost:" + ourPort + "/Observation/900");
status = ourClient.execute(httpGet);
extractResponseAndClose(status);
assertEquals(200, status.getStatusLine().getStatusCode());
assertTrue(ourHitMethod);
ourReturn = Collections.singletonList(createPatient(901));
ourHitMethod = false;
httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient/901");
status = ourClient.execute(httpGet);
extractResponseAndClose(status);
assertEquals(200, status.getStatusLine().getStatusCode());
assertTrue(ourHitMethod);
ourReturn = Collections.singletonList(createPatient(1));
ourHitMethod = false;
httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient/1?_format=json");
status = ourClient.execute(httpGet);
response = extractResponseAndClose(status);
assertEquals(403, status.getStatusLine().getStatusCode());
assertEquals(ERR403, response);
assertFalse(ourHitMethod);
}
@Test
public void testReadByInstanceAllowsTargetedSearch() throws Exception {
ourConditionalCreateId = "1";
ourServlet.registerInterceptor(new AuthorizationInterceptor(PolicyEnum.DENY) {
@Override
public List<IAuthRule> buildRuleList(RequestDetails theRequestDetails) {
RuleBuilder ruleBuilder = new RuleBuilder();
ruleBuilder.allow().read().instance("Patient/900").andThen();
ruleBuilder.allow().read().instance("Patient/700").andThen();
return ruleBuilder.build();
}
});
HttpResponse status;
String response;
HttpGet httpGet;
ourReturn = Collections.singletonList(createPatient(900));
ourHitMethod = false;
httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient?_id=900");
status = ourClient.execute(httpGet);
extractResponseAndClose(status);
assertEquals(200, status.getStatusLine().getStatusCode());
assertTrue(ourHitMethod);
ourHitMethod = false;
httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient?_id=Patient/900");
status = ourClient.execute(httpGet);
extractResponseAndClose(status);
assertEquals(200, status.getStatusLine().getStatusCode());
assertTrue(ourHitMethod);
ourHitMethod = false;
httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient?_id=901");
status = ourClient.execute(httpGet);
response = extractResponseAndClose(status);
assertEquals(403, status.getStatusLine().getStatusCode());
assertEquals(ERR403, response);
assertFalse(ourHitMethod);
ourHitMethod = false;
httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient?_id=Patient/901");
status = ourClient.execute(httpGet);
response = extractResponseAndClose(status);
assertEquals(403, status.getStatusLine().getStatusCode());
assertEquals(ERR403, response);
assertFalse(ourHitMethod);
ourHitMethod = false;
// technically this is invalid, but just in case..
httpGet = new HttpGet("http://localhost:" + ourPort + "/Observation?_id=Patient/901");
status = ourClient.execute(httpGet);
response = extractResponseAndClose(status);
assertEquals(403, status.getStatusLine().getStatusCode());
assertEquals(ERR403, response);
assertFalse(ourHitMethod);
ourHitMethod = false;
httpGet = new HttpGet("http://localhost:" + ourPort + "/Observation?_id=901");
status = ourClient.execute(httpGet);
response = extractResponseAndClose(status);
assertEquals(403, status.getStatusLine().getStatusCode());
assertEquals(ERR403, response);
assertFalse(ourHitMethod);
ourHitMethod = false;
httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient?_id=Patient/900,Patient/700");
status = ourClient.execute(httpGet);
extractResponseAndClose(status);
assertEquals(200, status.getStatusLine().getStatusCode());
assertTrue(ourHitMethod);
ourHitMethod = false;
httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient?_id=900,777");
status = ourClient.execute(httpGet);
extractResponseAndClose(status);
assertEquals(403, status.getStatusLine().getStatusCode());
assertFalse(ourHitMethod);
}
@Test
public void testReadPageRight() throws Exception {
ourServlet.registerInterceptor(new AuthorizationInterceptor(PolicyEnum.DENY) {
@Override
public List<IAuthRule> buildRuleList(RequestDetails theRequestDetails) {
return new RuleBuilder()
.allow("Rule 1").read().resourcesOfType(Observation.class).inCompartment("Patient", new IdType("Patient/1"))
.build();
}
});
HttpGet httpGet;
HttpResponse status;
String respString;
Bundle respBundle;
ourReturn = new ArrayList<>();
for (int i = 0; i < 10; i++) {
ourReturn.add(createObservation(i, "Patient/1"));
}
ourHitMethod = false;
httpGet = new HttpGet("http://localhost:" + ourPort + "/Observation?_count=5&_format=json&subject=Patient/1");
status = ourClient.execute(httpGet);
respString = extractResponseAndClose(status);
assertEquals(200, status.getStatusLine().getStatusCode());
assertTrue(ourHitMethod);
respBundle = ourCtx.newJsonParser().parseResource(Bundle.class, respString);
Assert.assertEquals(5, respBundle.getEntry().size());
Assert.assertEquals(10, respBundle.getTotal());
Assert.assertEquals("Observation/0", respBundle.getEntry().get(0).getResource().getIdElement().toUnqualifiedVersionless().getValue());
assertNotNull(respBundle.getLink("next"));
// Load next page
ourHitMethod = false;
httpGet = new HttpGet(respBundle.getLink("next").getUrl());
status = ourClient.execute(httpGet);
respString = extractResponseAndClose(status);
assertEquals(200, status.getStatusLine().getStatusCode());
assertFalse(ourHitMethod);
respBundle = ourCtx.newJsonParser().parseResource(Bundle.class, respString);
Assert.assertEquals(5, respBundle.getEntry().size());
Assert.assertEquals(10, respBundle.getTotal());
Assert.assertEquals("Observation/5", respBundle.getEntry().get(0).getResource().getIdElement().toUnqualifiedVersionless().getValue());
assertNull(respBundle.getLink("next"));
}
@Test
public void testReadPageWrong() throws Exception {
ourServlet.registerInterceptor(new AuthorizationInterceptor(PolicyEnum.DENY) {
@Override
public List<IAuthRule> buildRuleList(RequestDetails theRequestDetails) {
return new RuleBuilder()
.allow("Rule 1").read().resourcesOfType(Observation.class).inCompartment("Patient", new IdType("Patient/1"))
.build();
}
});
HttpGet httpGet;
HttpResponse status;
String respString;
Bundle respBundle;
ourReturn = new ArrayList<>();
for (int i = 0; i < 5; i++) {
ourReturn.add(createObservation(i, "Patient/1"));
}
for (int i = 5; i < 10; i++) {
ourReturn.add(createObservation(i, "Patient/2"));
}
ourHitMethod = false;
httpGet = new HttpGet("http://localhost:" + ourPort + "/Observation?_count=5&_format=json&subject=Patient/1");
status = ourClient.execute(httpGet);
respString = extractResponseAndClose(status);
assertEquals(200, status.getStatusLine().getStatusCode());
assertTrue(ourHitMethod);
respBundle = ourCtx.newJsonParser().parseResource(Bundle.class, respString);
Assert.assertEquals(5, respBundle.getEntry().size());
Assert.assertEquals(10, respBundle.getTotal());
Assert.assertEquals("Observation/0", respBundle.getEntry().get(0).getResource().getIdElement().toUnqualifiedVersionless().getValue());
assertNotNull(respBundle.getLink("next"));
// Load next page
ourHitMethod = false;
httpGet = new HttpGet(respBundle.getLink("next").getUrl());
status = ourClient.execute(httpGet);
extractResponseAndClose(status);
assertEquals(403, status.getStatusLine().getStatusCode());
assertFalse(ourHitMethod);
}
@Test
public void testTransactionWithSearch() throws IOException {
ourServlet.registerInterceptor(new AuthorizationInterceptor(PolicyEnum.DENY) {
@Override
public List<IAuthRule> buildRuleList(RequestDetails theRequestDetails) {
return new RuleBuilder()
.allow("transactions").transaction().withAnyOperation().andApplyNormalRules().andThen()
.allow("read patient").read().resourcesOfType(Patient.class).withAnyId().andThen()
.denyAll("deny all")
.build();
}
});
// Request is a transaction with 1 search
Bundle requestBundle = new Bundle();
requestBundle.setType(Bundle.BundleType.TRANSACTION);
String patientId = "10000003857";
Bundle.BundleEntryComponent bundleEntryComponent = requestBundle.addEntry();
Bundle.BundleEntryRequestComponent bundleEntryRequestComponent = new Bundle.BundleEntryRequestComponent();
bundleEntryRequestComponent.setMethod(Bundle.HTTPVerb.GET);
bundleEntryRequestComponent.setUrl(ResourceType.Patient + "?identifier=" + patientId);
bundleEntryComponent.setRequest(bundleEntryRequestComponent);
/*
* Response is a transaction response containing the search results
*/
Bundle searchResponseBundle = new Bundle();
Patient patent = new Patient();
patent.setActive(true);
patent.setId("Patient/123");
searchResponseBundle.addEntry().setResource(patent);
Bundle responseBundle = new Bundle();
responseBundle
.addEntry()
.setResource(searchResponseBundle);
ourReturn = Collections.singletonList(responseBundle);
HttpPost httpPost = new HttpPost("http://localhost:" + ourPort + "/");
httpPost.setEntity(createFhirResourceEntity(requestBundle));
CloseableHttpResponse status = ourClient.execute(httpPost);
String resp = extractResponseAndClose(status);
assertEquals(200, status.getStatusLine().getStatusCode());
}
@Test
public void testTransactionWithNoBundleType() throws IOException {
ourServlet.registerInterceptor(new AuthorizationInterceptor(PolicyEnum.DENY) {
@Override
public List<IAuthRule> buildRuleList(RequestDetails theRequestDetails) {
return new RuleBuilder()
.allow("transactions").transaction().withAnyOperation().andApplyNormalRules().andThen()
.allow("read patient").read().resourcesOfType(Patient.class).withAnyId().andThen()
.denyAll("deny all")
.build();
}
});
// Request is a transaction with 1 search
Bundle requestBundle = new Bundle();
String patientId = "10000003857";
Bundle.BundleEntryComponent bundleEntryComponent = requestBundle.addEntry();
Bundle.BundleEntryRequestComponent bundleEntryRequestComponent = new Bundle.BundleEntryRequestComponent();
bundleEntryRequestComponent.setMethod(Bundle.HTTPVerb.GET);
bundleEntryRequestComponent.setUrl(ResourceType.Patient + "?identifier=" + patientId);
bundleEntryComponent.setRequest(bundleEntryRequestComponent);
HttpPost httpPost = new HttpPost("http://localhost:" + ourPort + "/");
httpPost.setEntity(createFhirResourceEntity(requestBundle));
CloseableHttpResponse status = ourClient.execute(httpPost);
String resp = extractResponseAndClose(status);
assertEquals(422, status.getStatusLine().getStatusCode());
assertThat(resp, containsString("Invalid request Bundle.type value for transaction: \\\"\\\""));
}
/**
* See #762
*/
@Test
public void testTransactionWithPlaceholderIdsResponseAuthorized() throws IOException {
ourServlet.registerInterceptor(new AuthorizationInterceptor(PolicyEnum.DENY) {
@Override
public List<IAuthRule> buildRuleList(RequestDetails theRequestDetails) {
return new RuleBuilder()
.allow("transactions").transaction().withAnyOperation().andApplyNormalRules().andThen()
.allow("read patient").read().resourcesOfType(Patient.class).withAnyId().andThen()
.allow("write patient").write().resourcesOfType(Patient.class).withAnyId().andThen()
.allow("write encounter").write().resourcesOfType(Encounter.class).withAnyId().andThen()
.allow("write condition").write().resourcesOfType(Condition.class).withAnyId().andThen()
.denyAll("deny all")
.build();
}
});
Bundle input = createTransactionWithPlaceholdersRequestBundle();
Bundle output = createTransactionWithPlaceholdersResponseBundle();
ourReturn = Collections.singletonList(output);
HttpPost httpPost = new HttpPost("http://localhost:" + ourPort + "/");
httpPost.setEntity(createFhirResourceEntity(input));
CloseableHttpResponse status = ourClient.execute(httpPost);
String resp = extractResponseAndClose(status);
assertEquals(200, status.getStatusLine().getStatusCode());
ourLog.info(resp);
}
/**
* See #762
*/
@Test
public void testTransactionWithPlaceholderIdsResponseUnauthorized() throws IOException {
ourServlet.registerInterceptor(new AuthorizationInterceptor(PolicyEnum.DENY) {
@Override
public List<IAuthRule> buildRuleList(RequestDetails theRequestDetails) {
return new RuleBuilder()
.allow("transactions").transaction().withAnyOperation().andApplyNormalRules().andThen()
.allow("write patient").write().resourcesOfType(Patient.class).withAnyId().andThen()
.allow("write encounter").write().resourcesOfType(Encounter.class).withAnyId().andThen()
.allow("write condition").write().resourcesOfType(Condition.class).withAnyId().andThen()
.denyAll("deny all")
.build();
}
});
Bundle input = createTransactionWithPlaceholdersRequestBundle();
Bundle output = createTransactionWithPlaceholdersResponseBundle();
ourReturn = Collections.singletonList(output);
HttpPost httpPost = new HttpPost("http://localhost:" + ourPort + "/");
httpPost.setEntity(createFhirResourceEntity(input));
CloseableHttpResponse status = ourClient.execute(httpPost);
String resp = extractResponseAndClose(status);
assertEquals(403, status.getStatusLine().getStatusCode());
ourLog.info(resp);
}
@Test
public void testTransactionWriteGood() throws Exception {
ourServlet.registerInterceptor(new AuthorizationInterceptor(PolicyEnum.DENY) {
@Override
public List<IAuthRule> buildRuleList(RequestDetails theRequestDetails) {
return new RuleBuilder()
.allow("Rule 1").transaction().withAnyOperation().andApplyNormalRules().andThen()
.allow("Rule 2").write().allResources().inCompartment("Patient", new IdType("Patient/1")).andThen()
.allow("Rule 2").read().allResources().inCompartment("Patient", new IdType("Patient/1")).andThen()
.build();
}
});
Bundle input = new Bundle();
input.setType(Bundle.BundleType.TRANSACTION);
input.addEntry().setResource(createPatient(1)).getRequest().setUrl("/Patient").setMethod(Bundle.HTTPVerb.PUT);
Bundle output = new Bundle();
output.setType(Bundle.BundleType.TRANSACTIONRESPONSE);
output.addEntry().getResponse().setLocation("/Patient/1");
HttpPost httpPost;
HttpResponse status;
ourReturn = Collections.singletonList(output);
ourHitMethod = false;
httpPost = new HttpPost("http://localhost:" + ourPort + "/");
httpPost.setEntity(createFhirResourceEntity(input));
status = ourClient.execute(httpPost);
extractResponseAndClose(status);
assertEquals(200, status.getStatusLine().getStatusCode());
}
@Test
public void testWriteByCompartmentCreate() throws Exception {
ourServlet.registerInterceptor(new AuthorizationInterceptor(PolicyEnum.DENY) {
@Override
public List<IAuthRule> buildRuleList(RequestDetails theRequestDetails) {
return new RuleBuilder()
.allow("Rule 1").write().resourcesOfType(Patient.class).inCompartment("Patient", new IdType("Patient/1")).andThen()
.allow("Rule 1b").write().resourcesOfType(Patient.class).inCompartment("Patient", new IdType("Patient/1123")).andThen()
.allow("Rule 2").write().resourcesOfType(Observation.class).inCompartment("Patient", new IdType("Patient/1"))
.build();
}
});
HttpEntityEnclosingRequestBase httpPost;
HttpResponse status;
String response;
ourHitMethod = false;
httpPost = new HttpPost("http://localhost:" + ourPort + "/Patient");
httpPost.setEntity(createFhirResourceEntity(createPatient(null)));
status = ourClient.execute(httpPost);
response = extractResponseAndClose(status);
assertEquals(403, status.getStatusLine().getStatusCode());
assertEquals(ERR403, response);
assertFalse(ourHitMethod);
// Conditional
ourHitMethod = false;
httpPost = new HttpPost("http://localhost:" + ourPort + "/Patient");
httpPost.addHeader("If-None-Exist", "Patient?foo=bar");
httpPost.setEntity(createFhirResourceEntity(createPatient(null)));
status = ourClient.execute(httpPost);
response = extractResponseAndClose(status);
assertEquals(403, status.getStatusLine().getStatusCode());
assertEquals(ERR403, response);
assertFalse(ourHitMethod);
ourHitMethod = false;
httpPost = new HttpPost("http://localhost:" + ourPort + "/Observation");
httpPost.setEntity(createFhirResourceEntity(createObservation(null, "Patient/2")));
status = ourClient.execute(httpPost);
response = extractResponseAndClose(status);
assertEquals(403, status.getStatusLine().getStatusCode());
assertEquals(ERR403, response);
assertFalse(ourHitMethod);
ourHitMethod = false;
httpPost = new HttpPost("http://localhost:" + ourPort + "/Observation");
httpPost.setEntity(createFhirResourceEntity(createObservation(null, "Patient/1")));
status = ourClient.execute(httpPost);
extractResponseAndClose(status);
assertEquals(201, status.getStatusLine().getStatusCode());
assertTrue(ourHitMethod);
}
@Test
public void testWriteByCompartmentCreateConditionalResolvesToValid() throws Exception {
ourConditionalCreateId = "1";
ourServlet.registerInterceptor(new AuthorizationInterceptor(PolicyEnum.DENY) {
@Override
public List<IAuthRule> buildRuleList(RequestDetails theRequestDetails) {
return new RuleBuilder()
.allow("Rule 1").write().resourcesOfType(Patient.class).inCompartment("Patient", new IdType("Patient/1")).andThen()
.allow("Rule 2").createConditional().resourcesOfType(Patient.class)
.build();
}
});
HttpEntityEnclosingRequestBase httpPost;
HttpResponse status;
ourHitMethod = false;
httpPost = new HttpPost("http://localhost:" + ourPort + "/Patient");
httpPost.addHeader(Constants.HEADER_IF_NONE_EXIST, "foo=bar");
httpPost.setEntity(createFhirResourceEntity(createPatient(null)));
status = ourClient.execute(httpPost);
String response = extractResponseAndClose(status);
ourLog.info(response);
assertEquals(201, status.getStatusLine().getStatusCode());
assertTrue(ourHitMethod);
}
@Test
public void testWriteByCompartmentDeleteConditionalResolvesToValid() throws Exception {
ourConditionalCreateId = "1";
ourServlet.registerInterceptor(new AuthorizationInterceptor(PolicyEnum.DENY) {
@Override
public List<IAuthRule> buildRuleList(RequestDetails theRequestDetails) {
return new RuleBuilder()
.allow("Rule 1").delete().resourcesOfType(Patient.class).inCompartment("Patient", new IdType("Patient/1")).andThen()
.allow("Rule 2").deleteConditional().resourcesOfType(Patient.class)
.build();
}
});
HttpDelete httpDelete;
HttpResponse status;
ourReturn = Collections.singletonList(createPatient(1));
ourHitMethod = false;
httpDelete = new HttpDelete("http://localhost:" + ourPort + "/Patient?foo=bar");
status = ourClient.execute(httpDelete);
String response = extractResponseAndClose(status);
ourLog.info(response);
assertEquals(204, status.getStatusLine().getStatusCode());
assertTrue(ourHitMethod);
}
@Test
public void testWriteByCompartmentDeleteConditionalWithoutDirectMatch() throws Exception {
ourConditionalCreateId = "1";
ourServlet.registerInterceptor(new AuthorizationInterceptor(PolicyEnum.DENY) {
@Override
public List<IAuthRule> buildRuleList(RequestDetails theRequestDetails) {
return new RuleBuilder()
.allow("Rule 2").deleteConditional().resourcesOfType(Patient.class).andThen()
.allow().delete().instance(new IdType("Patient/2")).andThen()
.build();
}
});
HttpDelete httpDelete;
HttpResponse status;
String response;
// Wrong resource
ourReturn = Collections.singletonList(createPatient(1));
ourHitMethod = false;
httpDelete = new HttpDelete("http://localhost:" + ourPort + "/Patient?foo=bar");
status = ourClient.execute(httpDelete);
response = extractResponseAndClose(status);
ourLog.info(response);
assertEquals(403, status.getStatusLine().getStatusCode());
assertTrue(ourHitMethod);
// Right resource
ourReturn = Collections.singletonList(createPatient(2));
ourHitMethod = false;
httpDelete = new HttpDelete("http://localhost:" + ourPort + "/Patient?foo=bar");
status = ourClient.execute(httpDelete);
response = extractResponseAndClose(status);
ourLog.info(response);
assertEquals(204, status.getStatusLine().getStatusCode());
assertTrue(ourHitMethod);
}
@Test
public void testWriteByCompartmentDoesntAllowDelete() throws Exception {
ourServlet.registerInterceptor(new AuthorizationInterceptor(PolicyEnum.DENY) {
@Override
public List<IAuthRule> buildRuleList(RequestDetails theRequestDetails) {
return new RuleBuilder()
.allow("Rule 1").write().resourcesOfType(Patient.class).inCompartment("Patient", new IdType("Patient/1")).andThen()
.allow("Rule 2").write().resourcesOfType(Observation.class).inCompartment("Patient", new IdType("Patient/1"))
.build();
}
});
HttpDelete httpDelete;
HttpResponse status;
ourHitMethod = false;
ourReturn = Collections.singletonList(createPatient(2));
httpDelete = new HttpDelete("http://localhost:" + ourPort + "/Patient/2");
status = ourClient.execute(httpDelete);
extractResponseAndClose(status);
assertEquals(403, status.getStatusLine().getStatusCode());
assertFalse(ourHitMethod);
ourHitMethod = false;
ourReturn = Collections.singletonList(createPatient(1));
httpDelete = new HttpDelete("http://localhost:" + ourPort + "/Patient/1");
status = ourClient.execute(httpDelete);
extractResponseAndClose(status);
assertEquals(403, status.getStatusLine().getStatusCode());
assertFalse(ourHitMethod);
}
@Test
public void testWriteByCompartmentUpdate() throws Exception {
ourServlet.registerInterceptor(new AuthorizationInterceptor(PolicyEnum.DENY) {
@Override
public List<IAuthRule> buildRuleList(RequestDetails theRequestDetails) {
return new RuleBuilder()
.allow("Rule 1").write().resourcesOfType(Patient.class).inCompartment("Patient", new IdType("Patient/1")).andThen()
.allow("Rule 2").write().resourcesOfType(Observation.class).inCompartment("Patient", new IdType("Patient/1"))
.build();
}
});
HttpEntityEnclosingRequestBase httpPost;
String response;
HttpResponse status;
ourHitMethod = false;
httpPost = new HttpPut("http://localhost:" + ourPort + "/Patient/2");
httpPost.setEntity(createFhirResourceEntity(createPatient(2)));
status = ourClient.execute(httpPost);
response = extractResponseAndClose(status);
assertEquals(ERR403, response);
assertEquals(403, status.getStatusLine().getStatusCode());
assertFalse(ourHitMethod);
ourHitMethod = false;
httpPost = new HttpPut("http://localhost:" + ourPort + "/Patient/1");
httpPost.setEntity(createFhirResourceEntity(createPatient(1)));
status = ourClient.execute(httpPost);
extractResponseAndClose(status);
assertEquals(200, status.getStatusLine().getStatusCode());
assertTrue(ourHitMethod);
// Conditional
ourHitMethod = false;
httpPost = new HttpPut("http://localhost:" + ourPort + "/Patient?foo=bar");
httpPost.setEntity(createFhirResourceEntity(createPatient(1)));
status = ourClient.execute(httpPost);
response = extractResponseAndClose(status);
assertEquals(ERR403, response);
assertEquals(403, status.getStatusLine().getStatusCode());
assertFalse(ourHitMethod);
ourHitMethod = false;
httpPost = new HttpPut("http://localhost:" + ourPort + "/Patient?foo=bar");
httpPost.setEntity(createFhirResourceEntity(createPatient(99)));
status = ourClient.execute(httpPost);
response = extractResponseAndClose(status);
assertEquals(ERR403, response);
assertEquals(403, status.getStatusLine().getStatusCode());
assertFalse(ourHitMethod);
ourHitMethod = false;
httpPost = new HttpPut("http://localhost:" + ourPort + "/Observation/10");
httpPost.setEntity(createFhirResourceEntity(createObservation(10, "Patient/1")));
status = ourClient.execute(httpPost);
extractResponseAndClose(status);
assertEquals(200, status.getStatusLine().getStatusCode());
assertTrue(ourHitMethod);
ourHitMethod = false;
httpPost = new HttpPut("http://localhost:" + ourPort + "/Observation/10");
httpPost.setEntity(createFhirResourceEntity(createObservation(10, "Patient/2")));
status = ourClient.execute(httpPost);
response = extractResponseAndClose(status);
assertEquals(ERR403, response);
assertEquals(403, status.getStatusLine().getStatusCode());
assertFalse(ourHitMethod);
}
@Test
public void testWriteByCompartmentUpdateConditionalResolvesToInvalid() throws Exception {
ourConditionalCreateId = "1123";
ourServlet.registerInterceptor(new AuthorizationInterceptor(PolicyEnum.DENY) {
@Override
public List<IAuthRule> buildRuleList(RequestDetails theRequestDetails) {
return new RuleBuilder()
.allow("Rule 1").write().resourcesOfType(Patient.class).inCompartment("Patient", new IdType("Patient/1")).andThen()
.allow("Rule 2").write().resourcesOfType(Observation.class).inCompartment("Patient", new IdType("Patient/1")).andThen()
.allow("Rule 3").updateConditional().resourcesOfType(Patient.class)
.build();
}
});
HttpEntityEnclosingRequestBase httpPost;
HttpResponse status;
String response;
ourHitMethod = false;
httpPost = new HttpPut("http://localhost:" + ourPort + "/Patient?foo=bar");
httpPost.setEntity(createFhirResourceEntity(createPatient(null)));
status = ourClient.execute(httpPost);
response = extractResponseAndClose(status);
assertEquals(403, status.getStatusLine().getStatusCode());
assertEquals(ERR403, response);
assertTrue(ourHitMethod);
}
@Test
public void testWriteByCompartmentUpdateConditionalResolvesToValid() throws Exception {
ourConditionalCreateId = "1";
ourServlet.registerInterceptor(new AuthorizationInterceptor(PolicyEnum.DENY) {
@Override
public List<IAuthRule> buildRuleList(RequestDetails theRequestDetails) {
return new RuleBuilder()
.allow("Rule 1").write().resourcesOfType(Patient.class).inCompartment("Patient", new IdType("Patient/1")).andThen()
.allow("Rule 2").write().resourcesOfType(Observation.class).inCompartment("Patient", new IdType("Patient/1")).andThen()
.allow("Rule 3").updateConditional().resourcesOfType(Patient.class)
.build();
}
});
HttpEntityEnclosingRequestBase httpPost;
HttpResponse status;
String response;
ourHitMethod = false;
httpPost = new HttpPut("http://localhost:" + ourPort + "/Patient?foo=bar");
httpPost.setEntity(createFhirResourceEntity(createPatient(null)));
status = ourClient.execute(httpPost);
extractResponseAndClose(status);
assertEquals(200, status.getStatusLine().getStatusCode());
assertTrue(ourHitMethod);
ourHitMethod = false;
httpPost = new HttpPut("http://localhost:" + ourPort + "/Observation?foo=bar");
httpPost.setEntity(createFhirResourceEntity(createObservation(null, "Patient/12")));
status = ourClient.execute(httpPost);
response = extractResponseAndClose(status);
assertEquals(403, status.getStatusLine().getStatusCode());
assertEquals(ERR403, response);
assertFalse(ourHitMethod);
}
@Test
public void testWriteByCompartmentUpdateConditionalResolvesToValidAllTypes() throws Exception {
ourConditionalCreateId = "1";
ourServlet.registerInterceptor(new AuthorizationInterceptor(PolicyEnum.DENY) {
@Override
public List<IAuthRule> buildRuleList(RequestDetails theRequestDetails) {
return new RuleBuilder()
.allow("Rule 1").write().resourcesOfType(Patient.class).inCompartment("Patient", new IdType("Patient/1")).andThen()
.allow("Rule 2").write().resourcesOfType(Observation.class).inCompartment("Patient", new IdType("Patient/1")).andThen()
.allow("Rule 3").updateConditional().allResources()
.build();
}
});
HttpEntityEnclosingRequestBase httpPost;
HttpResponse status;
String response;
ourHitMethod = false;
httpPost = new HttpPut("http://localhost:" + ourPort + "/Patient?foo=bar");
httpPost.setEntity(createFhirResourceEntity(createPatient(null)));
status = ourClient.execute(httpPost);
extractResponseAndClose(status);
assertEquals(200, status.getStatusLine().getStatusCode());
assertTrue(ourHitMethod);
ourHitMethod = false;
httpPost = new HttpPut("http://localhost:" + ourPort + "/Observation?foo=bar");
httpPost.setEntity(createFhirResourceEntity(createObservation(null, "Patient/12")));
status = ourClient.execute(httpPost);
response = extractResponseAndClose(status);
assertTrue(ourHitMethod);
assertEquals(403, status.getStatusLine().getStatusCode());
assertEquals(ERR403, response);
}
@Test
public void testWriteByInstance() throws Exception {
ourConditionalCreateId = "1";
ourServlet.registerInterceptor(new AuthorizationInterceptor(PolicyEnum.DENY) {
@Override
public List<IAuthRule> buildRuleList(RequestDetails theRequestDetails) {
return new RuleBuilder()
.allow("Rule 1").write().instance("Observation/900").andThen()
.allow("Rule 1").write().instance("901").andThen()
.build();
}
});
HttpEntityEnclosingRequestBase httpPost;
HttpResponse status;
String response;
ourHitMethod = false;
httpPost = new HttpPut("http://localhost:" + ourPort + "/Observation/900");
httpPost.setEntity(createFhirResourceEntity(createObservation(900, "Patient/12")));
status = ourClient.execute(httpPost);
extractResponseAndClose(status);
assertEquals(200, status.getStatusLine().getStatusCode());
assertTrue(ourHitMethod);
ourHitMethod = false;
httpPost = new HttpPut("http://localhost:" + ourPort + "/Observation/901");
httpPost.setEntity(createFhirResourceEntity(createObservation(901, "Patient/12")));
status = ourClient.execute(httpPost);
extractResponseAndClose(status);
assertEquals(200, status.getStatusLine().getStatusCode());
assertTrue(ourHitMethod);
ourHitMethod = false;
httpPost = new HttpPost("http://localhost:" + ourPort + "/Observation");
httpPost.setEntity(createFhirResourceEntity(createObservation(null, "Patient/900")));
status = ourClient.execute(httpPost);
response = extractResponseAndClose(status);
assertEquals(403, status.getStatusLine().getStatusCode());
assertEquals(ERR403, response);
assertFalse(ourHitMethod);
ourHitMethod = false;
httpPost = new HttpPost("http://localhost:" + ourPort + "/Patient");
httpPost.setEntity(createFhirResourceEntity(createPatient(null)));
status = ourClient.execute(httpPost);
response = extractResponseAndClose(status);
assertEquals(403, status.getStatusLine().getStatusCode());
assertEquals(ERR403, response);
assertFalse(ourHitMethod);
}
@Test
public void testWritePatchByInstance() throws Exception {
ourConditionalCreateId = "1";
ourServlet.registerInterceptor(new AuthorizationInterceptor(PolicyEnum.DENY) {
@Override
public List<IAuthRule> buildRuleList(RequestDetails theRequestDetails) {
return new RuleBuilder()
.allow("Rule 1").patch().allRequests().andThen()
.allow("Rule 1").write().instance("Patient/900").andThen()
.build();
}
});
HttpEntityEnclosingRequestBase httpPost;
HttpResponse status;
String input = "[ { \"op\": \"replace\", \"path\": \"/gender\", \"value\": \"male\" } ]";
ourHitMethod = false;
httpPost = new HttpPatch("http://localhost:" + ourPort + "/Patient/900");
httpPost.setEntity(new StringEntity(input, ContentType.parse("application/json-patch+json")));
status = ourClient.execute(httpPost);
extractResponseAndClose(status);
assertEquals(200, status.getStatusLine().getStatusCode());
assertTrue(ourHitMethod);
}
public static class DummyCarePlanResourceProvider implements IResourceProvider {
@Override
public Class<? extends IBaseResource> getResourceType() {
return CarePlan.class;
}
@Read(version = true)
public CarePlan read(@IdParam IdType theId) {
ourHitMethod = true;
if (ourReturn.isEmpty()) {
throw new ResourceNotFoundException(theId);
}
return (CarePlan) ourReturn.get(0);
}
@Search()
public List<Resource> search() {
ourHitMethod = true;
return ourReturn;
}
}
@SuppressWarnings("unused")
public static class DummyEncounterResourceProvider implements IResourceProvider {
@Operation(name = "everything", idempotent = true)
public Bundle everything(@IdParam IdType theId) {
ourHitMethod = true;
Bundle retVal = new Bundle();
for (Resource next : ourReturn) {
retVal.addEntry().setResource(next);
}
return retVal;
}
@Override
public Class<? extends IBaseResource> getResourceType() {
return Encounter.class;
}
}
public static class DummyOrganizationResourceProvider implements IResourceProvider {
@Override
public Class<? extends IBaseResource> getResourceType() {
return Organization.class;
}
/**
* This should come before operation1
*/
@Operation(name = "opName", idempotent = true)
public Parameters operation0(@IdParam(optional = true) IdType theId) {
ourHitMethod = true;
return (Parameters) new Parameters().setId("1");
}
}
public static class DummyDiagnosticReportResourceProvider implements IResourceProvider {
@Override
public Class<? extends IBaseResource> getResourceType() {
return DiagnosticReport.class;
}
@Search()
public List<Resource> search(
@OptionalParam(name = "subject") ReferenceParam theSubject,
@OptionalParam(name = "patient") ReferenceParam thePatient
) {
ourHitMethod = true;
return ourReturn;
}
}
@SuppressWarnings("unused")
public static class DummyObservationResourceProvider implements IResourceProvider {
@Create()
public MethodOutcome create(@ResourceParam Observation theResource, @ConditionalUrlParam String theConditionalUrl) {
ourHitMethod = true;
theResource.setId("Observation/1/_history/1");
MethodOutcome retVal = new MethodOutcome();
retVal.setCreated(true);
retVal.setResource(theResource);
return retVal;
}
@Delete()
public MethodOutcome delete(@IdParam IdType theId) {
ourHitMethod = true;
return new MethodOutcome();
}
@Override
public Class<? extends IBaseResource> getResourceType() {
return Observation.class;
}
/**
* This should come before operation1
*/
@Operation(name = "opName", idempotent = true)
public Parameters operation0(@IdParam IdType theId) {
ourHitMethod = true;
return (Parameters) new Parameters().setId("1");
}
/**
* This should come after operation0
*/
@Operation(name = "opName", idempotent = true)
public Parameters operation1() {
ourHitMethod = true;
return (Parameters) new Parameters().setId("1");
}
@Patch
public MethodOutcome patch(@IdParam IdType theId, PatchTypeEnum thePatchType, @ResourceParam String theBody) {
ourHitMethod = true;
return new MethodOutcome().setId(theId.withVersion("2"));
}
@Read(version = true)
public Observation read(@IdParam IdType theId) {
ourHitMethod = true;
if (ourReturn.isEmpty()) {
throw new ResourceNotFoundException(theId);
}
return (Observation) ourReturn.get(0);
}
@Search()
public List<Resource> search(
@OptionalParam(name = "_id") TokenAndListParam theIds,
@OptionalParam(name = "subject") ReferenceParam theSubject) {
ourHitMethod = true;
return ourReturn;
}
@Update()
public MethodOutcome update(@IdParam IdType theId, @ResourceParam Observation theResource, @ConditionalUrlParam String theConditionalUrl, RequestDetails theRequestDetails) {
ourHitMethod = true;
if (isNotBlank(theConditionalUrl)) {
IdType actual = new IdType("Observation", ourConditionalCreateId);
ActionRequestDetails subRequest = new ActionRequestDetails(theRequestDetails, actual);
subRequest.notifyIncomingRequestPreHandled(RestOperationTypeEnum.UPDATE);
theResource.setId(actual);
} else {
ActionRequestDetails subRequest = new ActionRequestDetails(theRequestDetails, theResource);
subRequest.notifyIncomingRequestPreHandled(RestOperationTypeEnum.UPDATE);
theResource.setId(theId.withVersion("2"));
}
MethodOutcome retVal = new MethodOutcome();
retVal.setResource(theResource);
return retVal;
}
}
@SuppressWarnings("unused")
public static class DummyPatientResourceProvider implements IResourceProvider {
@Create()
public MethodOutcome create(@ResourceParam Patient theResource, @ConditionalUrlParam String theConditionalUrl, RequestDetails theRequestDetails) {
if (isNotBlank(theConditionalUrl)) {
IdType actual = new IdType("Patient", ourConditionalCreateId);
ActionRequestDetails subRequest = new ActionRequestDetails(theRequestDetails, actual);
subRequest.notifyIncomingRequestPreHandled(RestOperationTypeEnum.CREATE);
} else {
ActionRequestDetails subRequest = new ActionRequestDetails(theRequestDetails, theResource);
subRequest.notifyIncomingRequestPreHandled(RestOperationTypeEnum.CREATE);
}
ourHitMethod = true;
theResource.setId("Patient/1/_history/1");
MethodOutcome retVal = new MethodOutcome();
retVal.setCreated(true);
retVal.setResource(theResource);
return retVal;
}
@Delete()
public MethodOutcome delete(IInterceptorBroadcaster theRequestOperationCallback, @IdParam IdType theId, @ConditionalUrlParam String theConditionalUrl, RequestDetails theRequestDetails) {
ourHitMethod = true;
for (IBaseResource next : ourReturn) {
HookParams params = new HookParams()
.add(IBaseResource.class, next)
.add(RequestDetails.class, theRequestDetails)
.addIfMatchesType(ServletRequestDetails.class, theRequestDetails);
theRequestOperationCallback.callHooks(Pointcut.STORAGE_PRESTORAGE_RESOURCE_DELETED, params);
}
return new MethodOutcome();
}
@Operation(name = "everything", idempotent = true)
public Bundle everything(@IdParam IdType theId) {
ourHitMethod = true;
Bundle retVal = new Bundle();
for (Resource next : ourReturn) {
retVal.addEntry().setResource(next);
}
return retVal;
}
@Override
public Class<? extends IBaseResource> getResourceType() {
return Patient.class;
}
@History()
public List<Resource> history() {
ourHitMethod = true;
return (ourReturn);
}
@History()
public List<Resource> history(@IdParam IdType theId) {
ourHitMethod = true;
return (ourReturn);
}
@Operation(name = "opName", idempotent = true)
public Parameters operation0(@IdParam IdType theId) {
ourHitMethod = true;
return (Parameters) new Parameters().setId("1");
}
/**
* More generic method second to make sure that the
* other method takes precedence
*/
@Operation(name = "opName", idempotent = true)
public Parameters operation1() {
ourHitMethod = true;
return (Parameters) new Parameters().setId("1");
}
@Operation(name = "opName2", idempotent = true)
public Parameters operation2(@IdParam IdType theId) {
ourHitMethod = true;
return (Parameters) new Parameters().setId("1");
}
@Operation(name = "opName2", idempotent = true)
public Parameters operation2() {
ourHitMethod = true;
return (Parameters) new Parameters().setId("1");
}
@Patch()
public MethodOutcome patch(@IdParam IdType theId, @ResourceParam String theResource, PatchTypeEnum thePatchType) {
ourHitMethod = true;
MethodOutcome retVal = new MethodOutcome();
return retVal;
}
@Read(version = true)
public Patient read(@IdParam IdType theId) {
ourHitMethod = true;
if (ourReturn.isEmpty()) {
throw new ResourceNotFoundException(theId);
}
return (Patient) ourReturn.get(0);
}
@Search()
public List<Resource> search(@OptionalParam(name = "_id") TokenAndListParam theIdParam) {
ourHitMethod = true;
return ourReturn;
}
@Update()
public MethodOutcome update(@IdParam IdType theId, @ResourceParam Patient theResource, @ConditionalUrlParam String theConditionalUrl, RequestDetails theRequestDetails) {
ourHitMethod = true;
if (isNotBlank(theConditionalUrl)) {
IdType actual = new IdType("Patient", ourConditionalCreateId);
ActionRequestDetails subRequest = new ActionRequestDetails(theRequestDetails, actual);
subRequest.notifyIncomingRequestPreHandled(RestOperationTypeEnum.UPDATE);
theResource.setId(actual);
} else {
ActionRequestDetails subRequest = new ActionRequestDetails(theRequestDetails, theResource);
subRequest.notifyIncomingRequestPreHandled(RestOperationTypeEnum.UPDATE);
theResource.setId(theId.withVersion("2"));
}
MethodOutcome retVal = new MethodOutcome();
retVal.setResource(theResource);
return retVal;
}
@Validate
public MethodOutcome validate(@ResourceParam Patient theResource, @IdParam IdType theId, @ResourceParam String theRawResource, @ResourceParam EncodingEnum theEncoding,
@Validate.Mode ValidationModeEnum theMode, @Validate.Profile String theProfile, RequestDetails theRequestDetails) {
ourHitMethod = true;
OperationOutcome oo = new OperationOutcome();
oo.addIssue().setDiagnostics("OK");
return new MethodOutcome(oo);
}
@Validate
public MethodOutcome validate(@ResourceParam Patient theResource, @ResourceParam String theRawResource, @ResourceParam EncodingEnum theEncoding, @Validate.Mode ValidationModeEnum theMode,
@Validate.Profile String theProfile, RequestDetails theRequestDetails) {
ourHitMethod = true;
OperationOutcome oo = new OperationOutcome();
oo.addIssue().setDiagnostics("OK");
return new MethodOutcome(oo);
}
}
public static class PlainProvider {
@History()
public List<Resource> history() {
ourHitMethod = true;
return (ourReturn);
}
@Operation(name = "opName", idempotent = true)
public Parameters operation() {
ourHitMethod = true;
return (Parameters) new Parameters().setId("1");
}
@Operation(name = "process-message", idempotent = true)
public Parameters processMessage(@OperationParam(name = "content") Bundle theInput) {
ourHitMethod = true;
return (Parameters) new Parameters().setId("1");
}
@GraphQL
public String processGraphQlRequest(ServletRequestDetails theRequestDetails, @IdParam IIdType theId, @GraphQLQuery String theQuery) {
ourHitMethod = true;
return "{'foo':'bar'}";
}
@Transaction()
public Bundle search(ServletRequestDetails theRequestDetails, IInterceptorBroadcaster theInterceptorBroadcaster, @TransactionParam Bundle theInput) {
ourHitMethod = true;
if (ourDeleted != null) {
for (IBaseResource next : ourDeleted) {
HookParams params = new HookParams()
.add(IBaseResource.class, next)
.add(RequestDetails.class, theRequestDetails)
.add(ServletRequestDetails.class, theRequestDetails);
theInterceptorBroadcaster.callHooks(Pointcut.STORAGE_PRESTORAGE_RESOURCE_DELETED, params);
}
}
return (Bundle) ourReturn.get(0);
}
}
@AfterClass
public static void afterClassClearContext() throws Exception {
JettyUtil.closeServer(ourServer);
TestUtil.clearAllStaticFieldsForUnitTest();
}
@BeforeClass
public static void beforeClass() throws Exception {
ourServer = new Server(0);
DummyPatientResourceProvider patProvider = new DummyPatientResourceProvider();
DummyObservationResourceProvider obsProv = new DummyObservationResourceProvider();
DummyOrganizationResourceProvider orgProv = new DummyOrganizationResourceProvider();
DummyEncounterResourceProvider encProv = new DummyEncounterResourceProvider();
DummyCarePlanResourceProvider cpProv = new DummyCarePlanResourceProvider();
DummyDiagnosticReportResourceProvider drProv = new DummyDiagnosticReportResourceProvider();
PlainProvider plainProvider = new PlainProvider();
ServletHandler proxyHandler = new ServletHandler();
ourServlet = new RestfulServer(ourCtx);
ourServlet.setFhirContext(ourCtx);
ourServlet.setResourceProviders(patProvider, obsProv, encProv, cpProv, orgProv, drProv);
ourServlet.setPlainProviders(plainProvider);
ourServlet.setPagingProvider(new FifoMemoryPagingProvider(100));
ourServlet.setDefaultResponseEncoding(EncodingEnum.JSON);
ServletHolder servletHolder = new ServletHolder(ourServlet);
|
package org.helioviewer.plugins.eveplugin.view;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Date;
import javax.swing.BoxLayout;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JLabel;
import javax.swing.JPanel;
import org.helioviewer.base.math.Interval;
import org.helioviewer.jhv.gui.IconBank;
import org.helioviewer.jhv.gui.IconBank.JHVIcon;
import org.helioviewer.jhv.gui.dialogs.observation.ObservationDialog;
import org.helioviewer.jhv.layers.LayersListener;
import org.helioviewer.jhv.layers.LayersModel;
import org.helioviewer.plugins.eveplugin.controller.ZoomController;
import org.helioviewer.plugins.eveplugin.events.model.EventModel;
import org.helioviewer.plugins.eveplugin.events.model.EventModelListener;
import org.helioviewer.plugins.eveplugin.settings.EVESettings;
import org.helioviewer.plugins.eveplugin.view.linedataselector.LineDataSelectorPanel;
import org.helioviewer.viewmodel.view.View;
/**
*
*
* @author Bram Bourgoignie (Bram.Bourgoignie@oma.be)
*
*/
public class ControlsPanel extends JPanel implements ActionListener, LayersListener, EventModelListener {
private static final long serialVersionUID = 3639870635351984819L;
private static ControlsPanel singletongInstance;
private final JPanel lineDataSelectorContainer = new JPanel();
private final ImageIcon addIcon = IconBank.getIcon(JHVIcon.ADD);
private final JButton addLayerButton = new JButton("Add Layer", addIcon);
// private final String[] plots = { "No Events", "Events on Plot 1",
// "Events on Plot 2" };
// private final JComboBox eventsComboBox = new JComboBox(plots);
private final JCheckBox eventsCheckBox = new JCheckBox();
private final JLabel eventsLabel = new JLabel("Display events: ");
private final ImageIcon movietimeIcon = IconBank.getIcon(JHVIcon.LAYER_MOVIE_TIME);
private final JButton periodFromLayersButton = new JButton(movietimeIcon);
private ControlsPanel() {
initVisualComponents();
LayersModel.getSingletonInstance().addLayersListener(this);
}
private void initVisualComponents() {
EventModel.getSingletonInstance().addEventModelListener(this);
eventsCheckBox.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if (eventsCheckBox.isSelected()) {
EventModel.getSingletonInstance().activateEvents();
} else {
EventModel.getSingletonInstance().deactivateEvents();
}
}
});
addLayerButton.setToolTipText("Add a new layer");
addLayerButton.addActionListener(this);
periodFromLayersButton.setToolTipText("Request data of selected movie interval");
periodFromLayersButton.setPreferredSize(new Dimension(movietimeIcon.getIconWidth() + 14,
periodFromLayersButton.getPreferredSize().height));
periodFromLayersButton.addActionListener(this);
setEnabledStateOfPeriodMovieButton();
// this.setPreferredSize(new Dimension(100, 300));
lineDataSelectorContainer.setLayout(new BoxLayout(lineDataSelectorContainer, BoxLayout.Y_AXIS));
lineDataSelectorContainer.setPreferredSize(new Dimension(100, 130));
this.setLayout(new BorderLayout());
add(lineDataSelectorContainer, BorderLayout.CENTER);
JPanel pageEndPanel = new JPanel();
pageEndPanel.setBackground(Color.BLUE);
JPanel flowPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT));
flowPanel.add(eventsLabel);
flowPanel.add(eventsCheckBox);
flowPanel.add(periodFromLayersButton);
flowPanel.add(addLayerButton);
add(flowPanel, BorderLayout.PAGE_END);
}
public static ControlsPanel getSingletonInstance() {
if (singletongInstance == null) {
singletongInstance = new ControlsPanel();
}
return singletongInstance;
}
public void addLineDataSelector(LineDataSelectorPanel lineDataSelectorPanel) {
lineDataSelectorContainer.add(lineDataSelectorPanel);
}
public void removeLineDataSelector(LineDataSelectorPanel lineDataSelectorPanel) {
lineDataSelectorContainer.remove(lineDataSelectorPanel);
}
@Override
public void actionPerformed(ActionEvent e) {
if (e.getSource().equals(addLayerButton)) {
ObservationDialog.getSingletonInstance().showDialog(EVESettings.OBSERVATION_UI_NAME);
} else if (e.getSource() == periodFromLayersButton) {
final Interval<Date> interval = new Interval<Date>(LayersModel.getSingletonInstance().getFirstDate(), LayersModel
.getSingletonInstance().getLastDate());
ZoomController.getSingletonInstance().setSelectedInterval(interval, true);
}
}
private void setEnabledStateOfPeriodMovieButton() {
final Interval<Date> frameInterval = LayersModel.getSingletonInstance().getFrameInterval();
periodFromLayersButton.setEnabled(frameInterval.getStart() != null && frameInterval.getEnd() != null);
}
@Override
public void layerAdded(int idx) {
if (EventQueue.isDispatchThread()) {
setEnabledStateOfPeriodMovieButton();
} else {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
setEnabledStateOfPeriodMovieButton();
}
});
}
}
@Override
public void layerRemoved(View oldView, int oldIdx) {
if (EventQueue.isDispatchThread()) {
setEnabledStateOfPeriodMovieButton();
} else {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
setEnabledStateOfPeriodMovieButton();
}
});
}
}
@Override
public void layerChanged(int idx) {
// TODO Auto-generated method stub
}
@Override
public void activeLayerChanged(int idx) {
// TODO Auto-generated method stub
}
@Override
public void viewportGeometryChanged() {
// TODO Auto-generated method stub
}
@Override
public void timestampChanged(int idx) {
// TODO Auto-generated method stub
}
@Override
public void subImageDataChanged() {
// TODO Auto-generated method stub
}
@Override
public void layerDownloaded(int idx) {
// TODO Auto-generated method stub
}
@Override
public void eventsDeactivated() {
eventsCheckBox.setSelected(false);
repaint();
}
}
|
package com.highcharts.export.pool;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import javax.annotation.PostConstruct;
import org.apache.log4j.Logger;
import com.highcharts.export.server.Server;
import com.highcharts.export.server.ServerState;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.Enumeration;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
import org.apache.commons.io.IOUtils;
public class ServerObjectFactory implements ObjectFactory<Server> {
public String exec;
public String script;
private String host;
private int basePort;
private int readTimeout;
private int connectTimeout;
private int maxTimeout;
public static String tmpDir = System.getProperty("java.io.tmpdir");
private static HashMap<Integer, PortStatus> portUsage = new HashMap<Integer, PortStatus>();
protected static Logger logger = Logger.getLogger("pool");
private enum PortStatus {
BUSY,
FREE;
}
@Override
public Server create() {
logger.debug("in makeObject, " + exec + ", " + script + ", " + host);
Integer port = this.getAvailablePort();
portUsage.put(port, PortStatus.BUSY);
return new Server(exec, script, host, port, connectTimeout, readTimeout, maxTimeout);
}
@Override
public boolean validate(Server server) {
boolean isValid = false;
try {
if(server.getState() != ServerState.IDLE) {
logger.debug("server didn\'t pass validation");
return false;
}
String result = server.request("{\"status\":\"isok\"}");
if(result.indexOf("OK") > -1) {
isValid = true;
logger.debug("server passed validation");
} else {
logger.debug("server didn\'t pass validation");
}
} catch (Exception e) {
logger.error("Error while validating object in Pool: " + e.getMessage());
}
return isValid;
}
@Override
public void destroy(Server server) {
ServerObjectFactory.releasePort(server.getPort());
server.cleanup();
}
@Override
public void activate(Server server) {
server.setState(ServerState.ACTIVE);
}
@Override
public void passivate(Server server) {
server.setState(ServerState.IDLE);
}
public static void releasePort(Integer port) {
logger.debug("Releasing port " + port);
portUsage.put(port, PortStatus.FREE);
}
public Integer getAvailablePort() {
for (Map.Entry<Integer, PortStatus> entry : portUsage.entrySet()) {
if (PortStatus.FREE == entry.getValue()) {
// return available port
logger.debug("Portusage " + portUsage.toString());
return entry.getKey();
}
}
// if no port is free
logger.debug("Nothing free in Portusage " + portUsage.toString());
return basePort + portUsage.size();
}
/*Getters and Setters*/
public String getExec() {
return exec;
}
public void setExec(String exec) {
this.exec = exec;
}
public String getScript() {
return script;
}
public void setScript(String script) {
this.script = script;
}
public String getHost() {
return host;
}
public void setHost(String host) {
this.host = host;
}
public int getBasePort() {
return basePort;
}
public void setBasePort(int basePort) {
this.basePort = basePort;
}
public int getReadTimeout() {
return readTimeout;
}
public void setReadTimeout(int readTimeout) {
this.readTimeout = readTimeout;
}
public int getConnectTimeout() {
return connectTimeout;
}
public void setConnectTimeout(int connectTimeout) {
this.connectTimeout = connectTimeout;
}
public int getMaxTimeout() {
return maxTimeout;
}
public void setMaxTimeout(int maxTimeout) {
this.maxTimeout = maxTimeout;
}
@PostConstruct
public void afterBeanInit() {
String jarLocation = getClass().getProtectionDomain().getCodeSource().getLocation().getPath();
try {
jarLocation = URLDecoder.decode(jarLocation, "utf-8");
// get filesystem depend path
jarLocation = new File(jarLocation).getCanonicalPath();
} catch (UnsupportedEncodingException ueex) {
logger.error(ueex);
} catch (IOException ioex) {
logger.error(ioex);
}
try {
JarFile jar = new JarFile(jarLocation);
for (Enumeration<JarEntry> entries = jar.entries(); entries.hasMoreElements();) {
JarEntry entry = entries.nextElement();
String name = entry.getName();
if (name.startsWith("phantomjs/")) {
File file = new File(tmpDir + name);
if (name.endsWith("/")) {
file.mkdir();
} else {
InputStream in = jar.getInputStream(entry);
IOUtils.copy(in, new FileOutputStream(file));
}
}
}
} catch (IOException ioex) {
logger.error(ioex);
}
}
}
|
package net.ttddyy.evernote.rest;
import org.junit.Test;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.verify;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
/**
* Miscellaneous tests for {@link StoreOperationController}.
*
* @author Tadaya Tsuyukubo
*/
public class StoreOperationControllerMiscIntegrationTest extends AbstractStoreOperationControllerIntegrationTest {
@Test
public void testNoInputForNoParameterMethod() throws Exception {
given(userStoreOperations.isBusinessUser()).willReturn(true);
mockMvc.perform(post("/userStore/isBusinessUser"));
verify(userStoreOperations).isBusinessUser();
}
}
|
package org.springframework.data.gclouddatastore.repository;
import static org.hamcrest.Matchers.contains;
import static org.hamcrest.Matchers.instanceOf;
import java.net.URI;
import java.nio.charset.Charset;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.OffsetDateTime;
import java.time.ZonedDateTime;
import java.time.ZoneId;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.junit.Assert;
import org.junit.Test;
import org.springframework.data.gclouddatastore.repository.Unmarshaller;
import org.springframework.data.annotation.Id;
import com.google.cloud.Timestamp;
import com.google.cloud.datastore.Blob;
import com.google.cloud.datastore.DoubleValue;
import com.google.cloud.datastore.Entity;
import com.google.cloud.datastore.Key;
import com.google.cloud.datastore.LongValue;
import com.google.cloud.datastore.StringValue;
public class UnmarshallerTest {
@Data
@NoArgsConstructor
public static class TestBean {
@Id
long id;
Object object;
byte[] bytes;
String string;
Boolean boxedBoolean;
boolean primitiveBoolean;
Double boxedDouble;
double primitiveDouble;
Float boxedFloat;
float primitiveFloat;
Long boxedLong;
long primitiveLong;
Integer boxedInteger;
int primitiveInt;
Short boxedShort;
short primitiveShort;
Byte boxedByte;
byte primitiveByte;
List<?> list;
LinkedList<?> linkedList;
Map<String, Object> map;
URI uri;
Instant instant;
Date date;
Calendar calendar;
java.sql.Timestamp sqlTimestamp;
LocalDateTime localDateTime;
OffsetDateTime offsetDateTime;
ZonedDateTime zonedDateTime;
}
@Test
public void testUnmarshalToObject_Blob() {
//Setup
byte[] hello = "hello".getBytes(Charset.forName("UTF-8"));
Key key = Key.newBuilder("project", "kind", 1).build();
Entity entity = Entity.newBuilder(key)
.set("object", Blob.copyFrom(hello))
.set("bytes", Blob.copyFrom(hello))
.set("string", Blob.copyFrom(hello))
.build();
Unmarshaller unmarshaller = new Unmarshaller();
TestBean bean = new TestBean();
// Exercise
unmarshaller.unmarshalToObject(entity, bean);
// Verify
Assert.assertArrayEquals(hello, (byte[])bean.object);
Assert.assertArrayEquals(hello, bean.bytes);
Assert.assertEquals("hello", bean.string);
}
@Test
public void testUnmarshalToObject_Boolean() {
//Setup
Key key = Key.newBuilder("project", "kind", 1).build();
Entity entity = Entity.newBuilder(key)
.set("object", true)
.set("boxedBoolean", true)
.set("primitiveBoolean", true)
.build();
Unmarshaller unmarshaller = new Unmarshaller();
TestBean bean = new TestBean();
// Exercise
unmarshaller.unmarshalToObject(entity, bean);
// Verify
Assert.assertEquals(Boolean.TRUE, bean.object);
Assert.assertEquals(Boolean.TRUE, bean.boxedBoolean);
Assert.assertTrue(bean.primitiveBoolean);
}
@Test
public void testUnmarshalToObject_Double() {
//Setup
Key key = Key.newBuilder("project", "kind", 1).build();
Entity entity = Entity.newBuilder(key)
.set("object", 3.14)
.set("boxedDouble", 3.14)
.set("primitiveDouble", 3.14)
.set("boxedFloat", 3.14)
.set("primitiveFloat", 3.14)
.set("boxedLong", 3.14)
.set("primitiveLong", 3.14)
.set("boxedInteger", 3.14)
.set("primitiveInt", 3.14)
.set("boxedShort", 3.14)
.set("primitiveShort", 3.14)
.set("boxedByte", 3.14)
.set("primitiveByte", 3.14)
.build();
Unmarshaller unmarshaller = new Unmarshaller();
TestBean bean = new TestBean();
// Exercise
unmarshaller.unmarshalToObject(entity, bean);
// Verify
Assert.assertEquals(Double.valueOf(3.14), bean.object);
Assert.assertEquals(Double.valueOf(3.14), bean.boxedDouble);
Assert.assertEquals(3.14, bean.primitiveDouble, 0.0);
Assert.assertEquals(Float.valueOf(3.14f), bean.boxedFloat);
Assert.assertEquals(3.14f, bean.primitiveFloat, 0.0f);
Assert.assertEquals(Long.valueOf(3L), bean.boxedLong);
Assert.assertEquals(3, bean.primitiveLong);
Assert.assertEquals(Integer.valueOf(3), bean.boxedInteger);
Assert.assertEquals(3, bean.primitiveInt);
Assert.assertEquals(Short.valueOf((short)3), bean.boxedShort);
Assert.assertEquals(3, bean.primitiveShort);
Assert.assertEquals(Byte.valueOf((byte)3), bean.boxedByte);
Assert.assertEquals(3, bean.primitiveByte);
}
@Test
public void testUnmarshalToObject_Long() {
//Setup
Key key = Key.newBuilder("project", "kind", 1).build();
Entity entity = Entity.newBuilder(key)
.set("object", 42)
.set("boxedLong", 42)
.set("primitiveLong", 42)
.set("boxedInteger", 42)
.set("primitiveInt", 42)
.set("boxedShort", 42)
.set("primitiveShort", 42)
.set("boxedByte", 42)
.set("primitiveByte", 42)
.set("boxedDouble", 42)
.set("primitiveDouble", 42)
.set("boxedFloat", 42)
.set("primitiveFloat", 42)
.build();
Unmarshaller unmarshaller = new Unmarshaller();
TestBean bean = new TestBean();
// Exercise
unmarshaller.unmarshalToObject(entity, bean);
// Verify
Assert.assertEquals(Long.valueOf(42), bean.object);
Assert.assertEquals(Long.valueOf(42), bean.boxedLong);
Assert.assertEquals(42L, bean.primitiveLong);
Assert.assertEquals(Integer.valueOf(42), bean.boxedInteger);
Assert.assertEquals(42, bean.primitiveInt);
Assert.assertEquals(Short.valueOf((short)42), bean.boxedShort);
Assert.assertEquals(42, bean.primitiveShort);
Assert.assertEquals(Byte.valueOf((byte)42), bean.boxedByte);
Assert.assertEquals(42, bean.primitiveByte);
Assert.assertEquals(Double.valueOf(42.0), bean.boxedDouble);
Assert.assertEquals(42.0, bean.primitiveDouble, 0.0);
Assert.assertEquals(Float.valueOf(42.0f), bean.boxedFloat);
Assert.assertEquals(42.0f, bean.primitiveFloat, 0.0f);
}
@Test
public void testUnmarshalToObject_String() throws Exception {
//Setup
Key key = Key.newBuilder("project", "kind", 1).build();
Entity entity = Entity.newBuilder(key)
.set("object", "hello")
.set("string", "hello")
.set("bytes", "hello")
.set("boxedLong", "42")
.set("primitiveLong", "42")
.set("boxedInteger", "42")
.set("primitiveInt", "42")
.set("boxedShort", "42")
.set("primitiveShort", "42")
.set("boxedByte", "42")
.set("primitiveByte", "42")
.set("boxedDouble", "3.14")
.set("primitiveDouble", "3.14")
.set("boxedFloat", "3.14")
.set("primitiveFloat", "3.14")
.set("uri", "https://example.com")
.build();
Unmarshaller unmarshaller = new Unmarshaller();
TestBean bean = new TestBean();
// Exercise
unmarshaller.unmarshalToObject(entity, bean);
// Verify
Assert.assertEquals("hello", bean.object);
Assert.assertEquals("hello", bean.string);
Assert.assertArrayEquals("hello".getBytes(Charset.forName("UTF-8")), bean.bytes);
Assert.assertEquals(Long.valueOf(42), bean.boxedLong);
Assert.assertEquals(42L, bean.primitiveLong);
Assert.assertEquals(Integer.valueOf(42), bean.boxedInteger);
Assert.assertEquals(42, bean.primitiveInt);
Assert.assertEquals(Short.valueOf((short)42), bean.boxedShort);
Assert.assertEquals(42, bean.primitiveShort);
Assert.assertEquals(Byte.valueOf((byte)42), bean.boxedByte);
Assert.assertEquals(42, bean.primitiveByte);
Assert.assertEquals(Double.valueOf(3.14), bean.boxedDouble);
Assert.assertEquals(3.14, bean.primitiveDouble, 0.0);
Assert.assertEquals(Float.valueOf(3.14f), bean.boxedFloat);
Assert.assertEquals(3.14f, bean.primitiveFloat, 0.0f);
Assert.assertEquals(new URI("https://example.com"), bean.uri);
}
@Test
public void testUnmarshalToObject_List() {
//Setup
Key key = Key.newBuilder("project", "kind", 1).build();
Entity entity = Entity.newBuilder(key)
.set("object", Arrays.asList(DoubleValue.of(3.14), LongValue.of(42), StringValue.of("hello")))
.set("list", Arrays.asList(DoubleValue.of(3.14), LongValue.of(42), StringValue.of("hello")))
.set("linkedList", Arrays.asList(DoubleValue.of(3.14), LongValue.of(42), StringValue.of("hello")))
.build();
Unmarshaller unmarshaller = new Unmarshaller();
TestBean bean = new TestBean();
bean.linkedList = new LinkedList<Object>();
// Exercise
unmarshaller.unmarshalToObject(entity, bean);
// Verify
Assert.assertThat((List<?>)bean.object, contains(3.14, 42L, "hello"));
Assert.assertThat(bean.list, contains(3.14, 42L, "hello"));
Assert.assertThat(bean.linkedList, contains(3.14, 42L, "hello"));
Assert.assertThat(bean.linkedList, instanceOf(LinkedList.class));
}
@Test
public void testUnmarshalToObject_Map1() {
//Setup
Key key = Key.newBuilder("project", "kind", 1).build();
Entity entity = Entity.newBuilder(key)
.set("object", Entity.newBuilder().set("k", "v").build())
.set("map", Entity.newBuilder().set("k", "v").build())
.build();
Unmarshaller unmarshaller = new Unmarshaller();
TestBean bean = new TestBean();
// Exercise
unmarshaller.unmarshalToObject(entity, bean);
// Verify
Map<String, Object> expected = new HashMap<>();
expected.put("k", "v");
Assert.assertEquals(expected, bean.object);
Assert.assertEquals(expected, bean.map);
}
@Test
public void testUnmarshalToObject_Map2() {
//Setup
Key key = Key.newBuilder("project", "kind", 1).build();
Entity entity = Entity.newBuilder(key)
.set("object", Entity.newBuilder().set("k1",
Entity.newBuilder().set("k2", "v2").build()).build())
.set("map", Entity.newBuilder().set("k1",
Entity.newBuilder().set("k2", "v2").build()).build())
.build();
Unmarshaller unmarshaller = new Unmarshaller();
TestBean bean = new TestBean();
// Exercise
unmarshaller.unmarshalToObject(entity, bean);
// Verify
Map<String, Object> innerMap = new HashMap<>();
innerMap.put("k2", "v2");
Map<String, Object> expected = new HashMap<>();
expected.put("k1", innerMap);
Assert.assertEquals(expected, bean.object);
Assert.assertEquals(expected, bean.map);
}
@Test
public void testUnmarshalToObject_Timestamp() {
//Setup
Key key = Key.newBuilder("project", "kind", 1).build();
Entity entity = Entity.newBuilder(key)
.set("object", Timestamp.parseTimestamp("2017-07-09T12:34:56Z"))
.set("primitiveLong", Timestamp.parseTimestamp("2017-07-09T12:34:56Z"))
.set("boxedLong", Timestamp.parseTimestamp("2017-07-09T12:34:56Z"))
.set("date", Timestamp.parseTimestamp("2017-07-09T12:34:56Z"))
.set("calendar", Timestamp.parseTimestamp("2017-07-09T12:34:56Z"))
.set("sqlTimestamp", Timestamp.parseTimestamp("2017-07-09T12:34:56Z"))
.set("localDateTime", Timestamp.parseTimestamp("2017-07-09T12:34:56Z"))
.set("offsetDateTime", Timestamp.parseTimestamp("2017-07-09T12:34:56Z"))
.set("zonedDateTime", Timestamp.parseTimestamp("2017-07-09T12:34:56Z"))
.build();
Unmarshaller unmarshaller = new Unmarshaller();
TestBean bean = new TestBean();
// Exercise
unmarshaller.unmarshalToObject(entity, bean);
// Verify
Assert.assertEquals(
OffsetDateTime.parse("2017-07-09T12:34:56Z").toInstant(),
(Instant)bean.object);
Assert.assertEquals(
OffsetDateTime.parse("2017-07-09T12:34:56Z").toEpochSecond(),
bean.primitiveLong);
Assert.assertEquals(
Long.valueOf(OffsetDateTime.parse("2017-07-09T12:34:56Z").toEpochSecond()),
bean.boxedLong);
Assert.assertEquals(
Date.from(OffsetDateTime.parse("2017-07-09T12:34:56Z").toInstant()),
bean.date);
Assert.assertEquals(
new Calendar.Builder()
.setInstant(Date.from(OffsetDateTime.parse("2017-07-09T12:34:56Z").toInstant()))
.build(),
bean.calendar);
Assert.assertEquals(
java.sql.Timestamp.from(OffsetDateTime.parse("2017-07-09T12:34:56Z").toInstant()),
bean.sqlTimestamp);
Assert.assertEquals(
OffsetDateTime.parse("2017-07-09T12:34:56Z")
.atZoneSameInstant(ZoneId.systemDefault()).toLocalDateTime(),
bean.localDateTime);
Assert.assertEquals(
OffsetDateTime.parse("2017-07-09T12:34:56Z"),
bean.offsetDateTime);
Assert.assertEquals(
ZonedDateTime.parse("2017-07-09T12:34:56Z"),
bean.zonedDateTime);
}
}
|
package com.github.davidmoten.fsm.runtime.rx;
import java.util.ArrayDeque;
import java.util.Deque;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;
import com.github.davidmoten.fsm.runtime.CancelTimedSignal;
import com.github.davidmoten.fsm.runtime.Clock;
import com.github.davidmoten.fsm.runtime.EntityBehaviour;
import com.github.davidmoten.fsm.runtime.EntityStateMachine;
import com.github.davidmoten.fsm.runtime.Event;
import com.github.davidmoten.fsm.runtime.ObjectState;
import com.github.davidmoten.fsm.runtime.Search;
import com.github.davidmoten.fsm.runtime.Signal;
import com.github.davidmoten.guavamini.Preconditions;
import com.github.davidmoten.rx.Transformers;
import rx.Observable;
import rx.Observable.Transformer;
import rx.Observer;
import rx.Scheduler;
import rx.Scheduler.Worker;
import rx.Subscription;
import rx.functions.Action1;
import rx.functions.Func1;
import rx.observables.GroupedObservable;
import rx.observables.SyncOnSubscribe;
import rx.schedulers.Schedulers;
import rx.subjects.PublishSubject;
public final class Processor<Id> {
private final Func1<Class<?>, EntityBehaviour<?, Id>> behaviourFactory;
private final PublishSubject<Signal<?, Id>> subject;
private final Scheduler signalScheduler;
private final Scheduler processingScheduler;
private final Map<ClassId<?, Id>, EntityStateMachine<?, Id>> stateMachines = new ConcurrentHashMap<>();
private final Map<ClassIdPair<Id>, Subscription> subscriptions = new ConcurrentHashMap<>();
private final Observable<Signal<?, Id>> signals;
private final Func1<GroupedObservable<ClassId<?, Id>, EntityStateMachine<?, Id>>, Observable<EntityStateMachine<?, Id>>> entityTransform;
private final Transformer<Signal<?, Id>, Signal<?, Id>> preGroupBy;
private final Func1<Action1<ClassId<?, Id>>, Map<ClassId<?, Id>, Object>> mapFactory; // nullable
private final Clock signallerClock;
private final Search<Id> search = new Search<Id>() {
@Override
public <T> Optional<T> search(Class<T> cls, Id id) {
return getStateMachine(cls, id).get();
}
};
private Processor(Func1<Class<?>, EntityBehaviour<?, Id>> behaviourFactory,
Scheduler processingScheduler, Scheduler signalScheduler,
Observable<Signal<?, Id>> signals,
Func1<GroupedObservable<ClassId<?, Id>, EntityStateMachine<?, Id>>, Observable<EntityStateMachine<?, Id>>> entityTransform,
Transformer<Signal<?, Id>, Signal<?, Id>> preGroupBy,
Func1<Action1<ClassId<?, Id>>, Map<ClassId<?, Id>, Object>> mapFactory) {
Preconditions.checkNotNull(behaviourFactory);
Preconditions.checkNotNull(signalScheduler);
Preconditions.checkNotNull(signals);
Preconditions.checkNotNull(entityTransform);
Preconditions.checkNotNull(preGroupBy);
// mapFactory is nullable
this.behaviourFactory = behaviourFactory;
this.signalScheduler = signalScheduler;
this.processingScheduler = processingScheduler;
this.subject = PublishSubject.create();
this.signals = signals;
this.entityTransform = entityTransform;
this.preGroupBy = preGroupBy;
this.mapFactory = mapFactory;
this.signallerClock = Clock.from(signalScheduler);
}
public static <Id> Builder<Id> behaviourFactory(
Func1<Class<?>, EntityBehaviour<?, Id>> behaviourFactory) {
return new Builder<Id>().behaviourFactory(behaviourFactory);
}
public static <T, Id> Builder<Id> behaviour(Class<T> cls, EntityBehaviour<T, Id> behaviour) {
return new Builder<Id>().behaviour(cls, behaviour);
}
public static <Id> Builder<Id> signalScheduler(Scheduler signalScheduler) {
return new Builder<Id>().signalScheduler(signalScheduler);
}
public static <Id> Builder<Id> processingScheduler(Scheduler processingScheduler) {
return new Builder<Id>().processingScheduler(processingScheduler);
}
public static class Builder<Id> {
private Func1<Class<?>, EntityBehaviour<?, Id>> behaviourFactory;
private Scheduler signalScheduler = Schedulers.computation();
private Scheduler processingScheduler = Schedulers.immediate();
private Observable<Signal<?, Id>> signals = Observable.empty();
private Func1<GroupedObservable<ClassId<?, Id>, EntityStateMachine<?, Id>>, Observable<EntityStateMachine<?, Id>>> entityTransform = g -> g;
private Transformer<Signal<?, Id>, Signal<?, Id>> preGroupBy = x -> x;
private Func1<Action1<ClassId<?, Id>>, Map<ClassId<?, Id>, Object>> mapFactory; // nullable
private final Map<Class<?>, EntityBehaviour<?, Id>> behaviours = new HashMap<>();
private Builder() {
}
public <T> Builder<Id> behaviour(Class<T> cls, EntityBehaviour<T, Id> behaviour) {
behaviours.put(cls, behaviour);
return this;
}
public Builder<Id> behaviourFactory(
Func1<Class<?>, EntityBehaviour<?, Id>> behaviourFactory) {
this.behaviourFactory = behaviourFactory;
return this;
}
public Builder<Id> signalScheduler(Scheduler signalScheduler) {
this.signalScheduler = signalScheduler;
return this;
}
public Builder<Id> processingScheduler(Scheduler processingScheduler) {
this.processingScheduler = processingScheduler;
return this;
}
public Builder<Id> signals(Observable<Signal<?, Id>> signals) {
this.signals = signals;
return this;
}
public Builder<Id> entityTransform(
Func1<GroupedObservable<ClassId<?, Id>, EntityStateMachine<?, Id>>, Observable<EntityStateMachine<?, Id>>> entityTransform) {
this.entityTransform = entityTransform;
return this;
}
public Builder<Id> preGroupBy(Transformer<Signal<?, Id>, Signal<?, Id>> preGroupBy) {
this.preGroupBy = preGroupBy;
return this;
}
public Builder<Id> mapFactory(
Func1<Action1<ClassId<?, Id>>, Map<ClassId<?, Id>, Object>> mapFactory) {
this.mapFactory = mapFactory;
return this;
}
public Processor<Id> build() {
Preconditions.checkArgument(behaviourFactory != null || !behaviours.isEmpty(),
"one of behaviourFactory or multiple calls to behaviour must be made (behaviour must be specified)");
Preconditions.checkArgument(behaviourFactory == null || behaviours.isEmpty(),
"cannot specify both behaviourFactory and behaviour");
if (!behaviours.isEmpty()) {
behaviourFactory = cls -> behaviours.get(cls);
}
return new Processor<Id>(behaviourFactory, processingScheduler, signalScheduler,
signals, entityTransform, preGroupBy, mapFactory);
}
}
public Observable<EntityStateMachine<?, Id>> observable() {
return Observable.defer(() -> {
Worker worker = signalScheduler.createWorker();
@SuppressWarnings({ "unchecked", "rawtypes" })
Observable<GroupedObservable<ClassId<?, Id>, Signal<?, Id>>> o1 = subject
.toSerialized()
.onBackpressureBuffer()
.mergeWith(signals)
.doOnUnsubscribe(() -> worker.unsubscribe())
.compose(preGroupBy)
.compose(Transformers
.<Signal<?, Id>, ClassId<?, Id>, Signal<?, Id>> groupByEvicting(
signal -> new ClassId(signal.cls(), signal.id()), x -> x,
mapFactory));
return o1.flatMap(g -> {
Observable<EntityStateMachine<?, Id>> obs = g
.flatMap(processLambda(worker, g))
.doOnNext(m -> stateMachines.put(g.getKey(), m))
.subscribeOn(processingScheduler);
return entityTransform.call(GroupedObservable.from(g.getKey(), obs));
});
});
}
private Func1<? super Signal<?, Id>, Observable<EntityStateMachine<?, Id>>> processLambda(
Worker worker, GroupedObservable<ClassId<?, Id>, Signal<?, Id>> g) {
return x -> process(g.getKey(), x.event(), worker);
}
private static final class Signals<Id> {
final Deque<Event<?>> signalsToSelf = new ArrayDeque<>();
final Deque<Signal<?, Id>> signalsToOther = new ArrayDeque<>();
}
private Observable<EntityStateMachine<?, Id>> process(ClassId<?, Id> cid, Event<?> x,
Worker worker) {
return Observable.create(new SyncOnSubscribe<Signals<Id>, EntityStateMachine<?, Id>>() {
@Override
protected Signals<Id> generateState() {
Signals<Id> signals = new Signals<>();
signals.signalsToSelf.offerFirst(x);
return signals;
}
@Override
protected Signals<Id> next(Signals<Id> signals,
Observer<? super EntityStateMachine<?, Id>> observer) {
@SuppressWarnings("unchecked")
EntityStateMachine<Object, Id> m = (EntityStateMachine<Object, Id>) getStateMachine(
cid.cls(), cid.id());
@SuppressWarnings("unchecked")
Event<Object> event = (Event<Object>) signals.signalsToSelf.pollLast();
if (event != null) {
applySignalToSelf(signals, observer, m, event);
} else {
applySignalsToOthers(cid, worker, signals);
observer.onCompleted();
}
return signals;
}
@SuppressWarnings("unchecked")
private <T> void applySignalToSelf(Signals<Id> signals,
Observer<? super EntityStateMachine<?, Id>> observer,
EntityStateMachine<T, Id> m, Event<T> event) {
m = m.signal(event);
// stateMachines.put(id, m);
observer.onNext(m);
List<Event<? super T>> list = m.signalsToSelf();
for (int i = list.size() - 1; i >= 0; i
signals.signalsToSelf.offerLast(list.get(i));
}
for (Signal<?, ?> signal : m.signalsToOther()) {
signals.signalsToOther.offerFirst((Signal<?, Id>) signal);
}
}
private void applySignalsToOthers(ClassId<?, Id> cid, Worker worker,
Signals<Id> signals) {
Signal<?, Id> signal;
while ((signal = signals.signalsToOther.pollLast()) != null) {
Signal<?, Id> s = signal;
if (signal.isImmediate()) {
subject.onNext(signal);
} else if (signal.event() instanceof CancelTimedSignal) {
cancel(signal);
} else {
long delayMs = signal.time().get() - worker.now();
if (delayMs <= 0) {
subject.onNext(signal);
} else {
scheduleSignal(cid, worker, signal, s, delayMs);
}
}
}
}
private void cancel(Signal<?, Id> signal) {
@SuppressWarnings("unchecked")
CancelTimedSignal<Id> s = ((CancelTimedSignal<Id>) signal.event());
@SuppressWarnings({ "unchecked", "rawtypes" })
Subscription sub = subscriptions
.remove(new ClassIdPair<Id>(new ClassId(s.fromClass(), s.fromId()),
new ClassId(signal.cls(), signal.id())));
if (sub != null) {
sub.unsubscribe();
}
}
private void scheduleSignal(ClassId<?, Id> from, Worker worker, Signal<?, Id> signal,
Signal<?, Id> s, long delayMs) {
// record pairwise signal so we can cancel it if
// desired
@SuppressWarnings({ "unchecked", "rawtypes" })
ClassIdPair<Id> idPair = new ClassIdPair<Id>(from,
new ClassId(signal.cls(), signal.id()));
long t1 = signalScheduler.now();
Subscription subscription = worker.schedule(() -> {
subject.onNext(s.now());
} , delayMs, TimeUnit.MILLISECONDS);
long t2 = signalScheduler.now();
worker.schedule(() -> {
subscriptions.remove(idPair);
} , delayMs - (t2 - t1), TimeUnit.MILLISECONDS);
Subscription previous = subscriptions.put(idPair, subscription);
if (previous != null) {
previous.unsubscribe();
}
}
});
}
@SuppressWarnings("unchecked")
private <T> EntityStateMachine<T, Id> getStateMachine(Class<T> cls, Id id) {
return (EntityStateMachine<T, Id>) stateMachines
.computeIfAbsent(new ClassId<T, Id>(cls, id),
clsId -> (EntityStateMachine<T, Id>) behaviourFactory.call(cls)
.create(id)
.withSearch(search)
.withClock(signallerClock));
}
public <T> Optional<T> getObject(Class<T> cls, Id id) {
return getStateMachine(cls, id).get();
}
public void signal(Signal<?, Id> signal) {
subject.onNext(signal);
}
public <T> void signal(Class<T> cls, Id id, Event<? super T> event) {
subject.onNext(Signal.create(cls, id, event));
}
public <T> void signal(ClassId<T, Id> cid, Event<? super T> event) {
signal(cid.cls(), cid.id(), event);
}
@SuppressWarnings("unchecked")
public <T> ObjectState<T> get(Class<T> cls, Id id) {
return (EntityStateMachine<T, Id>) stateMachines.get(new ClassId<T, Id>(cls, id));
}
public void onCompleted() {
subject.onCompleted();
}
public void cancelSignal(Class<?> fromClass, Id fromId, Class<?> toClass, Id toId) {
@SuppressWarnings({ "unchecked", "rawtypes" })
Subscription subscription = subscriptions.remove(
new ClassIdPair<Id>(new ClassId(fromClass, fromId), new ClassId(toClass, toId)));
if (subscription != null) {
subscription.unsubscribe();
}
}
public void cancelSignalToSelf(Class<?> cls, Id id) {
cancelSignal(cls, id, cls, id);
}
public void cancelSignalToSelf(ClassId<?, Id> cid) {
cancelSignalToSelf(cid.cls(), cid.id());
}
}
|
package com.github.davidmoten.fsm.runtime.rx;
import java.util.ArrayDeque;
import java.util.Deque;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;
import com.github.davidmoten.fsm.runtime.CancelTimedSignal;
import com.github.davidmoten.fsm.runtime.EntityStateMachine;
import com.github.davidmoten.fsm.runtime.Event;
import com.github.davidmoten.fsm.runtime.ObjectState;
import com.github.davidmoten.fsm.runtime.Signal;
import com.github.davidmoten.guavamini.Preconditions;
import rx.Observable;
import rx.Observer;
import rx.Scheduler;
import rx.Scheduler.Worker;
import rx.Subscription;
import rx.functions.Func2;
import rx.observables.SyncOnSubscribe;
import rx.schedulers.Schedulers;
import rx.subjects.PublishSubject;
public final class Processor<Id> {
private final Func2<Class<?>, Id, EntityStateMachine<?>> stateMachineFactory;
private final PublishSubject<Signal<?, Id, ?>> subject;
private final Scheduler signalScheduler;
private final Scheduler processingScheduler;
private final Map<ClassId<?>, EntityStateMachine<?>> stateMachines = new ConcurrentHashMap<>();
private final Map<ClassIdPair<Id>, Subscription> subscriptions = new ConcurrentHashMap<>();
private Processor(Func2<Class<?>, Id, EntityStateMachine<?>> stateMachineFactory,
Scheduler processingScheduler, Scheduler signalScheduler) {
Preconditions.checkNotNull(stateMachineFactory);
Preconditions.checkNotNull(signalScheduler);
this.stateMachineFactory = stateMachineFactory;
this.signalScheduler = signalScheduler;
this.processingScheduler = processingScheduler;
this.subject = PublishSubject.create();
}
public static <Id> Builder<Id> stateMachineFactory(
Func2<Class<?>, Id, EntityStateMachine<?>> stateMachineFactory) {
return new Builder<Id>().stateMachineFactory(stateMachineFactory);
}
public static <Id> Builder<Id> signalScheduler(Scheduler signalScheduler) {
return new Builder<Id>().signalScheduler(signalScheduler);
}
public static <Id> Builder<Id> processingScheduler(Scheduler processingScheduler) {
return new Builder<Id>().processingScheduler(processingScheduler);
}
public static class Builder<Id> {
private Func2<Class<?>, Id, EntityStateMachine<?>> stateMachineFactory;
private Scheduler signalScheduler = Schedulers.computation();
private Scheduler processingScheduler = Schedulers.immediate();
private Builder() {
}
public Builder<Id> stateMachineFactory(
Func2<Class<?>, Id, EntityStateMachine<?>> stateMachineFactory) {
this.stateMachineFactory = stateMachineFactory;
return this;
}
public Builder<Id> signalScheduler(Scheduler signalScheduler) {
this.signalScheduler = signalScheduler;
return this;
}
public Builder<Id> processingScheduler(Scheduler processingScheduler) {
this.processingScheduler = processingScheduler;
return this;
}
public Processor<Id> build() {
return new Processor<Id>(stateMachineFactory, processingScheduler, signalScheduler);
}
}
public Observable<EntityStateMachine<?>> observable() {
return Observable.defer(() -> {
Worker worker = signalScheduler.createWorker();
return subject
.toSerialized()
.doOnUnsubscribe(() -> worker.unsubscribe())
.groupBy(signal -> new ClassId<Id>(signal.cls(), signal.id()))
.flatMap(g -> g
.flatMap(x -> process(g.getKey(), x.event(), worker))
.doOnNext(m -> stateMachines.put(g.getKey(), m))
.subscribeOn(processingScheduler));
});
}
private static final class Signals<Id> {
final Deque<Event<?>> signalsToSelf = new ArrayDeque<>();
final Deque<Signal<?, Id, ?>> signalsToOther = new ArrayDeque<>();
}
private Observable<EntityStateMachine<?>> process(ClassId<Id> cid, Event<?> x, Worker worker) {
return Observable.create(new SyncOnSubscribe<Signals<Id>, EntityStateMachine<?>>() {
@Override
protected Signals<Id> generateState() {
Signals<Id> signals = new Signals<>();
signals.signalsToSelf.offerFirst(x);
return signals;
}
@Override
protected Signals<Id> next(Signals<Id> signals,
Observer<? super EntityStateMachine<?>> observer) {
EntityStateMachine<?> m = getStateMachine(cid.cls(), cid.id());
Event<?> event = signals.signalsToSelf.pollLast();
if (event != null) {
applySignalToSelf(signals, observer, m, event);
} else {
applySignalsToOthers(cid, worker, signals);
observer.onCompleted();
}
return signals;
}
@SuppressWarnings("unchecked")
private void applySignalToSelf(Signals<Id> signals,
Observer<? super EntityStateMachine<?>> observer, EntityStateMachine<?> m,
Event<?> event) {
m = m.signal(event);
// stateMachines.put(id, m);
observer.onNext(m);
List<Event<?>> list = m.signalsToSelf();
for (int i = list.size() - 1; i >= 0; i
signals.signalsToSelf.offerLast(list.get(i));
}
for (Signal<?, ?, ?> signal : m.signalsToOther()) {
signals.signalsToOther.offerFirst((Signal<?, Id, ?>) signal);
}
}
private void applySignalsToOthers(ClassId<Id> cid, Worker worker, Signals<Id> signals) {
Signal<?, Id, ?> signal;
while ((signal = signals.signalsToOther.pollLast()) != null) {
Signal<?, Id, ?> s = signal;
if (signal.isImmediate()) {
subject.onNext(signal);
} else if (signal.event() instanceof CancelTimedSignal) {
cancel(signal);
} else {
long delayMs = signal.time() - worker.now();
if (delayMs <= 0) {
subject.onNext(signal);
} else {
scheduleSignal(cid, worker, signal, s, delayMs);
}
}
}
}
private void cancel(Signal<?, Id, ?> signal) {
@SuppressWarnings("unchecked")
CancelTimedSignal<Id> s = ((CancelTimedSignal<Id>) signal.event());
Subscription sub = subscriptions
.remove(new ClassIdPair<Id>(new ClassId<Id>(s.fromClass(), s.fromId()),
new ClassId<Id>(signal.cls(), signal.id())));
if (sub != null) {
sub.unsubscribe();
}
}
private void scheduleSignal(ClassId<Id> from, Worker worker, Signal<?, Id, ?> signal,
Signal<?, Id, ?> s, long delayMs) {
// record pairwise signal so we can cancel it if
// desired
ClassIdPair<Id> idPair = new ClassIdPair<Id>(from,
new ClassId<Id>(signal.cls(), signal.id()));
long t1 = signalScheduler.now();
Subscription subscription = worker.schedule(() -> {
subject.onNext(s.now());
} , delayMs, TimeUnit.MILLISECONDS);
long t2 = signalScheduler.now();
worker.schedule(() -> {
subscriptions.remove(idPair);
} , delayMs - (t2 - t1), TimeUnit.MILLISECONDS);
Subscription previous = subscriptions.put(idPair, subscription);
if (previous != null) {
previous.unsubscribe();
}
}
});
}
@SuppressWarnings("unchecked")
private <T> EntityStateMachine<T> getStateMachine(Class<T> cls, Id id) {
EntityStateMachine<T> m = (EntityStateMachine<T>) stateMachines
.get(new ClassId<Id>(cls, id));
if (m == null) {
m = (EntityStateMachine<T>) stateMachineFactory.call(cls, id);
}
return m;
}
public <T> Optional<T> getObject(Class<T> cls, Id id) {
return getStateMachine(cls, id).get();
}
public void signal(Signal<?, Id, ?> signal) {
subject.onNext(signal);
}
public <T, R> void signal(Class<T> cls, Id id, Event<R> event) {
subject.onNext(Signal.create(cls, id, event));
}
public <T> void signal(ClassId<Id> cid, Event<T> event) {
subject.onNext(Signal.create(cid.cls(), cid.id(), event));
}
@SuppressWarnings("unchecked")
public <T> ObjectState<T> get(Class<T> cls, Id id) {
return (EntityStateMachine<T>) stateMachines.get(new ClassId<Id>(cls, id));
}
public void onCompleted() {
subject.onCompleted();
}
public void cancelSignal(Class<?> fromClass, Id fromId, Class<?> toClass, Id toId) {
Subscription subscription = subscriptions.remove(new ClassIdPair<Id>(
new ClassId<Id>(fromClass, fromId), new ClassId<Id>(toClass, toId)));
if (subscription != null) {
subscription.unsubscribe();
}
}
public void cancelSignalToSelf(Class<?> cls, Id id) {
cancelSignal(cls, id, cls, id);
}
public void cancelSignalToSelf(ClassId<Id> cid) {
cancelSignalToSelf(cid.cls(), cid.id());
}
}
|
package com.emc.mongoose.storage.mock.impl.base;
import com.emc.mongoose.common.collection.ListingLRUMap;
import com.emc.mongoose.common.concurrent.BlockingQueueTaskSequencer;
import com.emc.mongoose.common.concurrent.FutureTaskBase;
import com.emc.mongoose.model.api.data.ContentSource;
import com.emc.mongoose.model.impl.item.CsvFileItemInput;
import com.emc.mongoose.storage.mock.api.MutableDataItemMock;
import com.emc.mongoose.storage.mock.api.ObjectContainerMock;
import com.emc.mongoose.storage.mock.api.StorageIoStats;
import com.emc.mongoose.storage.mock.api.StorageMock;
import com.emc.mongoose.storage.mock.api.exception.ContainerMockException;
import com.emc.mongoose.storage.mock.api.exception.ContainerMockNotFoundException;
import com.emc.mongoose.storage.mock.api.exception.ObjectMockNotFoundException;
import com.emc.mongoose.storage.mock.api.exception.StorageMockCapacityLimitReachedException;
import com.emc.mongoose.ui.config.Config;
import com.emc.mongoose.ui.log.LogUtil;
import com.emc.mongoose.ui.log.Markers;
import org.apache.logging.log4j.Level;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import java.io.EOFException;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicLong;
public abstract class StorageMockBase<T extends MutableDataItemMock>
implements StorageMock<T> {
private static final Logger LOG = LogManager.getLogger();
private final AtomicBoolean started = new AtomicBoolean(false);
private final String dataSrcPath;
private final StorageIoStats ioStats;
protected final ContentSource contentSrc;
private final int storageCapacity, containerCapacity;
private final ListingLRUMap<String, ObjectContainerMock<T>> storageMap;
private final ObjectContainerMock<T> defaultContainer;
private volatile boolean isCapacityExhausted = false;
@SuppressWarnings("unchecked")
public StorageMockBase(
final Config.StorageConfig.MockConfig mockConfig,
final Config.LoadConfig.MetricsConfig metricsConfig,
final Config.ItemConfig itemConfig,
final ContentSource contentSrc
) {
super();
final Config.StorageConfig.MockConfig.ContainerConfig
containerConfig = mockConfig.getContainerConfig();
storageMap = new ListingLRUMap<>(containerConfig.getCountLimit());
this.dataSrcPath = itemConfig.getInputConfig().getFile();
this.contentSrc = contentSrc;
this.ioStats = new BasicStorageIoStats(this, (int) metricsConfig.getPeriod());
this.storageCapacity = mockConfig.getCapacity();
this.containerCapacity = containerConfig.getCapacity();
this.defaultContainer = new BasicObjectContainerMock<>(containerCapacity);
storageMap.put(getClass().getSimpleName().toLowerCase(), defaultContainer);
}
// Container methods
@Override
public final void createContainer(final String name) {
synchronized(storageMap) {
storageMap.put(name, new BasicObjectContainerMock<>(containerCapacity));
ioStats.containerCreate();
}
}
@Override
public final ObjectContainerMock<T> getContainer(final String name) {
synchronized(storageMap) {
return storageMap.get(name);
}
}
@Override
public final void deleteContainer(final String name) {
synchronized(storageMap) {
storageMap.remove(name);
ioStats.containerDelete();
}
}
// Object methods
protected abstract T newDataObject(final String id, final long offset, final long size);
@Override
public final void createObject(
final String containerName, final String id, final long offset, final long size
) throws ContainerMockNotFoundException, StorageMockCapacityLimitReachedException {
if(isCapacityExhausted) {
throw new StorageMockCapacityLimitReachedException();
}
final ObjectContainerMock<T> c = getContainer(containerName);
if(c != null) {
c.put(id, newDataObject(id, offset, size));
} else {
throw new ContainerMockNotFoundException(containerName);
}
}
@Override
public final void updateObject(
final String containerName, final String id, final long offset, final long size
) throws ContainerMockException, ObjectMockNotFoundException {
final ObjectContainerMock<T> c = getContainer(containerName);
if(c != null) {
final T obj = c.get(id);
if(obj != null) {
obj.update(offset, size);
} else {
throw new ObjectMockNotFoundException(id);
}
} else {
throw new ContainerMockNotFoundException(containerName);
}
}
@Override
public final void appendObject(
final String containerName, final String id, final long offset, final long size
) throws ContainerMockException, ObjectMockNotFoundException {
final ObjectContainerMock<T> c = getContainer(containerName);
if(c != null) {
final T obj = c.get(id);
if(obj != null) {
obj.append(offset, size);
} else {
throw new ObjectMockNotFoundException(id);
}
} else {
throw new ContainerMockNotFoundException(containerName);
}
}
@Override
public final T getObject(
final String containerName, final String id, final long offset, final long size
) throws ContainerMockException {
// TODO partial read using offset and size args
final ObjectContainerMock<T> c = getContainer(containerName);
if(c != null) {
return c.get(id);
} else {
throw new ContainerMockNotFoundException(containerName);
}
}
@Override
public final void deleteObject(
final String containerName, final String id, final long offset, final long size
) throws ContainerMockNotFoundException {
final ObjectContainerMock<T> c = getContainer(containerName);
if(c != null) {
c.remove(id);
} else {
throw new ContainerMockNotFoundException(containerName);
}
}
@Override
public final T listObjects(
final String containerName, final String afterObjectId, final Collection<T> outputBuffer,
final int limit
) throws ContainerMockException {
final ObjectContainerMock<T> container = getContainer(containerName);
if(container != null) {
return container.list(afterObjectId, outputBuffer, limit);
} else {
throw new ContainerMockNotFoundException(containerName);
}
}
private final Thread storageCapacityMonitorThread = new Thread("storageMockCapacityMonitor") {
{
setDaemon(true);
}
@SuppressWarnings("InfiniteLoopStatement")
@Override
public final void run() {
long currObjCount;
try {
while(true) {
TimeUnit.SECONDS.sleep(1);
currObjCount = getSize();
if(!isCapacityExhausted && currObjCount > storageCapacity) {
isCapacityExhausted = true;
} else if(isCapacityExhausted && currObjCount <= storageCapacity) {
isCapacityExhausted = false;
}
}
} catch(final InterruptedException ignored) {
}
}
};
@Override
public final void start() {
loadPersistedDataItems();
ioStats.start();
doStart();
storageCapacityMonitorThread.start();
started.set(true);
}
@Override
public final boolean isStarted() {
return started.get();
}
protected abstract void doStart();
@Override
public long getSize() {
long size = 0;
synchronized(storageMap) {
for(final ObjectContainerMock<T> container : storageMap.values()) {
size += container.size();
}
}
return size;
}
@Override
public long getCapacity() {
return storageCapacity;
}
@Override
public final void putIntoDefaultContainer(final List<T> dataItems) {
for(final T object : dataItems) {
defaultContainer.put(object.getName(), object);
}
}
@Override
public StorageIoStats getStats() {
return ioStats;
}
@SuppressWarnings({"InfiniteLoopStatement", "unchecked"})
private void loadPersistedDataItems() {
if(dataSrcPath != null && !dataSrcPath.isEmpty()) {
final Path dataFilePath = Paths.get(dataSrcPath);
if(!Files.exists(dataFilePath)) {
LOG.warn(
Markers.ERR, "Data item source file @ \"" + dataSrcPath + "\" doesn't exists"
);
return;
}
if(Files.isDirectory(dataFilePath)) {
LOG.warn(
Markers.ERR, "Data item source file @ \"" + dataSrcPath + "\" is a directory"
);
return;
}
if(Files.isReadable(dataFilePath)) {
LOG.debug(
Markers.ERR, "Data item source file @ \"" + dataSrcPath + "\" is not readable"
);
}
final AtomicLong count = new AtomicLong(0);
List<T> buff;
int n;
final Thread displayProgressThread = new Thread(() -> {
try {
while(true) {
LOG.info(Markers.MSG, "{} items loaded...", count.get());
TimeUnit.SECONDS.sleep(10);
}
} catch(final InterruptedException ignored) {
}
});
try(
final CsvFileItemInput<T>
csvFileItemInput = new CsvFileItemInput<>(
dataFilePath, (Class<T>) BasicMutableDataItemMock.class, contentSrc
)
) {
displayProgressThread.start();
do {
buff = new ArrayList<>(4096);
n = csvFileItemInput.get(buff, 4096);
if(n > 0) {
putIntoDefaultContainer(buff);
count.addAndGet(n);
} else {
break;
}
} while(true);
} catch(final EOFException e) {
LOG.info(Markers.MSG, "Loaded {} data items from file {}", count, dataFilePath);
} catch(final IOException | NoSuchMethodException e) {
LogUtil.exception(
LOG, Level.WARN, e, "Failed to load the data items from file \"{}\"",
dataFilePath
);
} finally {
displayProgressThread.interrupt();
}
}
}
private abstract class ContainerTaskBase
extends FutureTaskBase<T> {
private final String containerName;
public ContainerTaskBase(final String containerName) {
this.containerName = containerName;
}
public ObjectContainerMock<T> getContainer() {
return storageMap.get(containerName);
}
protected final boolean setException() {
return setException(
new ContainerMockNotFoundException(containerName)
);
}
}
private final class PutObjectsBatchTask
extends FutureTaskBase<List<T>> {
private final String containerName;
private final List<T> objects;
public PutObjectsBatchTask(final String containerName, final List<T> objects) {
this.containerName = containerName;
this.objects = objects;
}
@Override
public final void run() {
final ObjectContainerMock<T> container = storageMap.get(containerName);
if(container != null) {
objects.forEach(object -> container.put(object.getName(), object));
set(new ArrayList<>(container.values()));
} else {
setException(new ContainerMockNotFoundException(containerName));
}
}
}
private final class ListObjectsTask
extends ContainerTaskBase {
private final String afterObjectId;
private final Collection<T> outputBuffer;
private final int limit;
public ListObjectsTask(
final String containerName, final String afterObjectId,
final Collection<T> outputBuffer, final int limit
) {
super(containerName);
this.afterObjectId = afterObjectId;
this.outputBuffer = outputBuffer;
this.limit = limit;
}
@Override
public final void run() {
final ObjectContainerMock<T> container = getContainer();
if(container != null) {
set(container.list(afterObjectId, outputBuffer, limit));
} else {
setException();
}
}
}
private final class DeleteObjectTask
extends ContainerTaskBase {
private final String objectId;
public DeleteObjectTask(final String containerName, final String objectId) {
super(containerName);
this.objectId = objectId;
}
@Override
public final void run() {
final ObjectContainerMock<T> container = getContainer();
if(container != null) {
set(container.remove(objectId));
} else {
setException();
}
}
}
private final class GetObjectTask
extends ContainerTaskBase {
private final String objectId;
public GetObjectTask(final String containerName, final String objectId) {
super(containerName);
this.objectId = objectId;
}
@Override
public final void run() {
final ObjectContainerMock<T> container = getContainer();
if(container != null) {
set(container.get(objectId));
} else {
setException();
}
}
}
private final class PutObjectTask
extends ContainerTaskBase {
private T object;
public PutObjectTask(final String containerName, final T object) {
super(containerName);
this.object = object;
}
@Override
public final void run() {
final ObjectContainerMock<T> container =
getContainer();
if(container != null) {
set(container.put(object.getName(), object));
} else {
setException();
}
}
}
private final class DeleteContainerTask
extends FutureTaskBase<ObjectContainerMock<T>> {
private final String containerName;
public DeleteContainerTask(final String containerName) {
this.containerName = containerName;
}
@Override
public final void run() {
if(storageMap.containsKey(containerName)) {
set(storageMap.remove(containerName));
} else {
setException(new ContainerMockNotFoundException(containerName));
}
}
}
private final class GetContainerTask
extends FutureTaskBase<ObjectContainerMock<T>> {
private final String containerName;
public GetContainerTask(final String containerName) {
this.containerName = containerName;
}
@Override
public final void run() {
if(storageMap.containsKey(containerName)) {
set(storageMap.get(containerName));
} else {
setException(new ContainerMockNotFoundException(containerName));
}
}
}
private final class PutContainerTask
extends FutureTaskBase<ObjectContainerMock<T>> {
private final String containerName;
public PutContainerTask(final String containerName) {
this.containerName = containerName;
}
@Override
public final void run() {
set(storageMap.put(containerName, new BasicObjectContainerMock<>(containerCapacity)));
ioStats.containerCreate();
}
}
}
|
package org.duracloud.swiftstorage;
import static org.duracloud.common.error.RetryFlaggableException.NO_RETRY;
import static org.duracloud.common.error.RetryFlaggableException.RETRY;
import static org.duracloud.storage.provider.StorageProvider.PROPERTIES_CONTENT_CHECKSUM;
import static org.duracloud.storage.provider.StorageProvider.PROPERTIES_CONTENT_MD5;
import static org.duracloud.storage.provider.StorageProvider.PROPERTIES_CONTENT_MIMETYPE;
import static org.duracloud.storage.provider.StorageProvider.PROPERTIES_CONTENT_MODIFIED;
import static org.duracloud.storage.provider.StorageProvider.PROPERTIES_CONTENT_SIZE;
import static org.duracloud.storage.provider.StorageProvider.PROPERTIES_SPACE_COUNT;
import static org.duracloud.storage.provider.StorageProvider.PROPERTIES_SPACE_CREATED;
import java.lang.reflect.Field;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import com.amazonaws.AmazonClientException;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.Headers;
import com.amazonaws.services.s3.model.AccessControlList;
import com.amazonaws.services.s3.model.AmazonS3Exception;
import com.amazonaws.services.s3.model.Bucket;
import com.amazonaws.services.s3.model.CopyObjectRequest;
import com.amazonaws.services.s3.model.ObjectMetadata;
import org.apache.commons.lang.StringUtils;
import org.duracloud.common.constant.Constants;
import org.duracloud.common.rest.HttpHeaders;
import org.duracloud.s3storage.S3ProviderUtil;
import org.duracloud.s3storage.S3StorageProvider;
import org.duracloud.storage.domain.StorageProviderType;
import org.duracloud.storage.error.NotFoundException;
import org.duracloud.storage.error.StorageException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class SwiftStorageProvider extends S3StorageProvider {
private final Logger log =
LoggerFactory.getLogger(SwiftStorageProvider.class);
public SwiftStorageProvider(String accessKey, String secretKey, Map<String, String> options) {
super(accessKey, secretKey, options);
}
public SwiftStorageProvider(AmazonS3 s3Client, String accessKey) {
super(s3Client, accessKey, null);
}
private static String[] SWIFT_METADATA_LIST =
{Headers.ETAG, Headers.CONTENT_LENGTH, Headers.DATE, Headers.LAST_MODIFIED, Headers.CONTENT_TYPE};
/**
* {@inheritDoc}
*/
@Override
public StorageProviderType getStorageProviderType() {
return StorageProviderType.SWIFT_S3;
}
@Override
protected Bucket createBucket(String spaceId) {
String bucketName = getNewBucketName(spaceId);
try {
Bucket bucket = s3Client.createBucket(bucketName);
// Swift has no concept of bucket lifecycle
return bucket;
} catch (AmazonClientException e) {
String err = "Could not create Swift container with name " + bucketName
+ " due to error: " + e.getMessage();
throw new StorageException(err, e, RETRY);
}
}
@Override
public void removeSpace(String spaceId) {
// Will throw if bucket does not exist
String bucketName = getBucketName(spaceId);
String propertiesBucketName = getBucketName(PROPERTIES_BUCKET);
try {
s3Client.deleteBucket(bucketName);
} catch (AmazonClientException e) {
String err = "Could not delete Swift container with name " + bucketName
+ " due to error: " + e.getMessage();
throw new StorageException(err, e, RETRY);
}
// Space properties are stored as tags with the S3 bucket.
// So with Swift we need to delete the associated properties object in Swift.
s3Client.deleteObject(propertiesBucketName, spaceId);
}
@Override
public String createHiddenSpace(String spaceId, int expirationInDays) {
String bucketName = getHiddenBucketName(spaceId);
try {
Bucket bucket = s3Client.createBucket(bucketName);
return spaceId;
} catch (AmazonClientException e) {
String err = "Could not create Swift container with name " + bucketName
+ " due to error: " + e.getMessage();
throw new StorageException(err, e, RETRY);
}
}
// Swift access keys are longer than 20 characters, and creating
// a bucket starting with your access key causes problems.
@Override
protected String getNewBucketName(String spaceId) {
String truncatedKey = truncateKey(accessKeyId);
return S3ProviderUtil.createNewBucketName(truncatedKey, spaceId);
}
@Override
protected String getSpaceId(String bucketName) {
String spaceId = bucketName;
String truncatedKey = truncateKey(accessKeyId);
if (isSpace(bucketName)) {
spaceId = spaceId.substring(truncatedKey.length() + 1);
}
return spaceId;
}
@Override
protected Map<String, String> getAllSpaceProperties(String spaceId) {
log.debug("getAllSpaceProperties(" + spaceId + ")");
// Will throw if bucket does not exist
String propsBucketName = getBucketName(PROPERTIES_BUCKET);
Map<String, String> spaceProperties = new HashMap<>();
String spacePropertiesString;
try {
spacePropertiesString = s3Client.getObjectAsString(propsBucketName, spaceId);
// Remove the {} from the string
spacePropertiesString =
spacePropertiesString.substring(1, spacePropertiesString.length() - 1);
String[] spacePropertiesList = spacePropertiesString.split(", ");
for (String property : spacePropertiesList) {
String[] props = property.split("=");
spaceProperties.put(props[0], props[1]);
}
} catch (AmazonS3Exception e) {
// If no space properties have been set yet, then the object will not exist.
// But we don't need to create it here, as it gets created when properties are set.
log.debug(
"Metadata object for space " + spaceId +
" was not found in container " + propsBucketName +
", probably because this is a new space."
);
}
// Handle @ symbol (change from +), to allow for email usernames in ACLs
spaceProperties = replaceInMapValues(spaceProperties, "+", "@");
// Add space count
spaceProperties.put(PROPERTIES_SPACE_COUNT,
getSpaceCount(spaceId, MAX_ITEM_COUNT));
return spaceProperties;
}
@Override
protected void doSetSpaceProperties(String spaceId,
Map<String, String> spaceProperties) {
log.debug("setSpaceProperties(" + spaceId + ")");
Map<String, String> originalProperties;
try {
originalProperties = getAllSpaceProperties(spaceId);
} catch (NotFoundException e) {
// The metadata bucket does not exist yet, so create it
createHiddenSpace(PROPERTIES_BUCKET, 0);
// And set the original properties to a new, empty HashMap
originalProperties = new HashMap<>();
}
// By calling this _after_ we have requested the space properties,
// we ensure that the metadata bucket exists.
String metadataBucketName = getBucketName(PROPERTIES_BUCKET);
// Set creation date
String creationDate = originalProperties.get(PROPERTIES_SPACE_CREATED);
if (creationDate == null) {
creationDate = spaceProperties.get(PROPERTIES_SPACE_CREATED);
if (creationDate == null) {
// getCreationDate() does not work properly on Swift
creationDate = formattedDate(new Date());
}
}
spaceProperties.put(PROPERTIES_SPACE_CREATED, creationDate);
// Handle @ symbol (change to +), to allow for email usernames in ACLs
spaceProperties = replaceInMapValues(spaceProperties, "@", "+");
// Store properties in an object in the hidden metadata bucket
log.debug(
"Writing space properties " + spaceProperties.toString() +
" to object " + spaceId +
" in Swift container " + metadataBucketName
);
s3Client.putObject(metadataBucketName, spaceId, spaceProperties.toString());
}
@Override
protected void updateObjectProperties(String bucketName,
String contentId,
ObjectMetadata objMetadata) {
try {
AccessControlList originalACL =
s3Client.getObjectAcl(bucketName, contentId);
CopyObjectRequest copyRequest = new CopyObjectRequest(bucketName,
contentId,
bucketName,
contentId);
copyRequest.setStorageClass(DEFAULT_STORAGE_CLASS);
copyRequest.setNewObjectMetadata(objMetadata);
// Setting object ACLs resets an object's ContentType to application/xml!
// But setting the ACLs before we do the copy request gets around this.
copyRequest.setAccessControlList(originalACL);
s3Client.copyObject(copyRequest);
} catch (AmazonClientException e) {
throwIfContentNotExist(bucketName, contentId);
String err = "Could not update metadata for content " + contentId + " in Swift container " +
bucketName + " due to error: " + e.getMessage();
throw new StorageException(err, e, NO_RETRY);
}
}
@Override
protected Map<String, String> prepContentProperties(ObjectMetadata objMetadata) {
Map<String, String> contentProperties = new HashMap<>();
// Set the user properties
Map<String, String> userProperties = objMetadata.getUserMetadata();
for (String metaName : userProperties.keySet()) {
String metaValue = userProperties.get(metaName);
if (metaName.trim().equalsIgnoreCase("tags") ||
metaName.trim().equalsIgnoreCase("tags" + HEADER_KEY_SUFFIX) ||
metaName.trim().equalsIgnoreCase(PROPERTIES_CONTENT_MIMETYPE) ||
metaName.trim().equalsIgnoreCase(PROPERTIES_CONTENT_MIMETYPE + HEADER_KEY_SUFFIX)) {
metaName = metaName.toLowerCase();
}
contentProperties.put(getWithSpace(decodeHeaderKey(metaName)), decodeHeaderValue(metaValue));
}
// Set the response metadata
Map<String, Object> responseMeta = objMetadata.getRawMetadata();
for (String metaName : responseMeta.keySet()) {
// Don't include Swift response headers
try {
if (!isSwiftMetadata(metaName)) {
Object metaValue = responseMeta.get(metaName);
// Remove extra Swift metadata from user properties section
for (String swiftMetaName : SWIFT_METADATA_LIST) {
if (metaName.trim().equalsIgnoreCase(swiftMetaName)) {
metaName = swiftMetaName;
}
}
contentProperties.put(metaName, String.valueOf(metaValue));
}
} catch (IllegalArgumentException e) {
e.printStackTrace();
}
// Remove User Response headers that are also in RawMetadata
// Swift metadata are non-standard HTTP headers so DuraCloud views them as "User" metadata
if (userProperties.keySet()
.contains(metaName + HEADER_KEY_SUFFIX) && contentProperties.containsKey(metaName)) {
contentProperties.remove(metaName);
}
}
// Set MIMETYPE
String contentType = objMetadata.getContentType();
if (contentType != null) {
contentProperties.put(PROPERTIES_CONTENT_MIMETYPE, contentType);
contentProperties.put(Headers.CONTENT_TYPE, contentType);
}
// Set CONTENT_ENCODING
String encoding = objMetadata.getContentEncoding();
if (encoding != null) {
contentProperties.put(Headers.CONTENT_ENCODING, encoding);
}
// Set SIZE
long contentLength = objMetadata.getContentLength();
if (contentLength >= 0) {
String size = String.valueOf(contentLength);
contentProperties.put(PROPERTIES_CONTENT_SIZE, size);
contentProperties.put(Headers.CONTENT_LENGTH, size);
}
// Set CHECKSUM
String checksum = objMetadata.getETag();
if (checksum != null) {
String eTagValue = getETagValue(checksum);
contentProperties.put(PROPERTIES_CONTENT_CHECKSUM, eTagValue);
contentProperties.put(PROPERTIES_CONTENT_MD5, eTagValue);
contentProperties.put(Headers.ETAG, eTagValue);
}
// Set MODIFIED
Date modified = objMetadata.getLastModified();
if (modified != null) {
String modDate = formattedDate(modified);
contentProperties.put(PROPERTIES_CONTENT_MODIFIED, modDate);
contentProperties.put(Headers.LAST_MODIFIED, modDate);
}
return contentProperties;
}
private String truncateKey(String accessKey) {
// Convert access key to 20 character string
return StringUtils.left(accessKey, 20);
}
private boolean isSwiftMetadata(String metaName) {
Field[] httpFields = HttpHeaders.class.getFields();
for (Field f : httpFields) {
String fieldName = null;
try {
fieldName = (String) f.get(httpFields);
} catch (IllegalArgumentException | IllegalAccessException e) {
e.printStackTrace();
}
if (metaName.equalsIgnoreCase(fieldName)) {
return false;
}
}
return true;
}
/**
* Add expire header for object in Swift.
* @param bucketName
* @param contentId
* @param seconds
*/
public ObjectMetadata expireObject(String bucketName, String contentId, Integer seconds) {
log.debug("Expiring object {} in {} after {} seconds.", contentId, bucketName, seconds);
ObjectMetadata objMetadata = getObjectDetails(bucketName, contentId, true);
objMetadata.setHeader(Constants.SWIFT_EXPIRE_OBJECT_HEADER, seconds);
updateObjectProperties(bucketName, contentId, objMetadata);
return objMetadata;
}
private ObjectMetadata getObjectDetails(String bucketName, String contentId, boolean retry) {
try {
return s3Client.getObjectMetadata(bucketName, contentId);
} catch (AmazonClientException e) {
throwIfContentNotExist(bucketName, contentId);
String err = "Could not get details for content " + contentId + " in Swift container " + bucketName
+ " due to error: " + e.getMessage();
throw new StorageException(err, e, retry);
}
}
}
|
package org.telegram.telegrambots.meta.api.objects;
import com.fasterxml.jackson.annotation.JsonProperty;
import org.telegram.telegrambots.meta.api.interfaces.BotApiObject;
import org.telegram.telegrambots.meta.api.objects.games.Animation;
import org.telegram.telegrambots.meta.api.objects.games.Game;
import org.telegram.telegrambots.meta.api.objects.passport.PassportData;
import org.telegram.telegrambots.meta.api.objects.payments.Invoice;
import org.telegram.telegrambots.meta.api.objects.payments.SuccessfulPayment;
import org.telegram.telegrambots.meta.api.objects.stickers.Sticker;
import java.util.ArrayList;
import java.util.List;
/**
* @author Ruben Bermudez
* @version 1.0
* This object represents a message.
*/
public class Message implements BotApiObject {
private static final String MESSAGEID_FIELD = "message_id";
private static final String FROM_FIELD = "from";
private static final String DATE_FIELD = "date";
private static final String CHAT_FIELD = "chat";
private static final String FORWARDFROM_FIELD = "forward_from";
private static final String FORWARDFROMCHAT_FIELD = "forward_from_chat";
private static final String FORWARDDATE_FIELD = "forward_date";
private static final String TEXT_FIELD = "text";
private static final String ENTITIES_FIELD = "entities";
private static final String CAPTIONENTITIES_FIELD = "caption_entities";
private static final String AUDIO_FIELD = "audio";
private static final String DOCUMENT_FIELD = "document";
private static final String PHOTO_FIELD = "photo";
private static final String STICKER_FIELD = "sticker";
private static final String VIDEO_FIELD = "video";
private static final String CONTACT_FIELD = "contact";
private static final String LOCATION_FIELD = "location";
private static final String VENUE_FIELD = "venue";
private static final String ANIMATION_FIELD = "animation";
private static final String PINNED_MESSAGE_FIELD = "pinned_message";
private static final String NEWCHATMEMBERS_FIELD = "new_chat_members";
private static final String LEFTCHATMEMBER_FIELD = "left_chat_member";
private static final String NEWCHATTITLE_FIELD = "new_chat_title";
private static final String NEWCHATPHOTO_FIELD = "new_chat_photo";
private static final String DELETECHATPHOTO_FIELD = "delete_chat_photo";
private static final String GROUPCHATCREATED_FIELD = "group_chat_created";
private static final String REPLYTOMESSAGE_FIELD = "reply_to_message";
private static final String VOICE_FIELD = "voice";
private static final String CAPTION_FIELD = "caption";
private static final String SUPERGROUPCREATED_FIELD = "supergroup_chat_created";
private static final String CHANNELCHATCREATED_FIELD = "channel_chat_created";
private static final String MIGRATETOCHAT_FIELD = "migrate_to_chat_id";
private static final String MIGRATEFROMCHAT_FIELD = "migrate_from_chat_id";
private static final String EDITDATE_FIELD = "edit_date";
private static final String GAME_FIELD = "game";
private static final String FORWARDFROMMESSAGEID_FIELD = "forward_from_message_id";
private static final String INVOICE_FIELD = "invoice";
private static final String SUCCESSFUL_PAYMENT_FIELD = "successful_payment";
private static final String VIDEO_NOTE_FIELD = "video_note";
private static final String AUTHORSIGNATURE_FIELD = "author_signature";
private static final String FORWARDSIGNATURE_FIELD = "forward_signature";
private static final String MEDIAGROUPID_FIELD = "media_group_id";
private static final String CONNECTEDWEBSITE_FIELD = "connected_website";
private static final String PASSPORTDATA_FIELD = "passport_data";
@JsonProperty(MESSAGEID_FIELD)
private Integer messageId; ///< Integer Unique message identifier
@JsonProperty(FROM_FIELD)
private User from; ///< Optional. Sender, can be empty for messages sent to channels
@JsonProperty(DATE_FIELD)
private Integer date; ///< Optional. Date the message was sent in Unix time
@JsonProperty(CHAT_FIELD)
private Chat chat; ///< Conversation the message belongs to
@JsonProperty(FORWARDFROM_FIELD)
private User forwardFrom; ///< Optional. For forwarded messages, sender of the original message
@JsonProperty(FORWARDFROMCHAT_FIELD)
private Chat forwardFromChat; ///< Optional. For messages forwarded from a channel, information about the original channel
@JsonProperty(FORWARDDATE_FIELD)
private Integer forwardDate; ///< Optional. For forwarded messages, date the original message was sent
@JsonProperty(TEXT_FIELD)
private String text; ///< Optional. For text messages, the actual UTF-8 text of the message
/**
* Optional. For text messages, special entities like usernames, URLs,
* bot commands, etc. that appear in the text
*/
@JsonProperty(ENTITIES_FIELD)
private List<MessageEntity> entities;
/**
* Optional. For messages with a caption, special entities like usernames,
* URLs, bot commands, etc. that appear in the caption
*/
@JsonProperty(CAPTIONENTITIES_FIELD)
private List<MessageEntity> captionEntities;
@JsonProperty(AUDIO_FIELD)
private Audio audio; ///< Optional. Message is an audio file, information about the file
@JsonProperty(DOCUMENT_FIELD)
private Document document; ///< Optional. Message is a general file, information about the file
@JsonProperty(PHOTO_FIELD)
private List<PhotoSize> photo; ///< Optional. Message is a photo, available sizes of the photo
@JsonProperty(STICKER_FIELD)
private Sticker sticker; ///< Optional. Message is a sticker, information about the sticker
@JsonProperty(VIDEO_FIELD)
private Video video; ///< Optional. Message is a video, information about the video
@JsonProperty(CONTACT_FIELD)
private Contact contact; ///< Optional. Message is a shared contact, information about the contact
@JsonProperty(LOCATION_FIELD)
private Location location; ///< Optional. Message is a shared location, information about the location
@JsonProperty(VENUE_FIELD)
private Venue venue; ///< Optional. Message is a venue, information about the venue
/**
* Optional. Message is an animation, information about the animation.
* For backward compatibility, when this field is set, the document field will be also set
*/
@JsonProperty(ANIMATION_FIELD)
private Animation animation;
@JsonProperty(PINNED_MESSAGE_FIELD)
private Message pinnedMessage; ///< Optional. Specified message was pinned. Note that the Message object in this field will not contain further reply_to_message fields even if it is itself a reply.
@JsonProperty(NEWCHATMEMBERS_FIELD)
private List<User> newChatMembers; ///< Optional. New members were added to the group or supergroup, information about them (the bot itself may be one of these members)
@JsonProperty(LEFTCHATMEMBER_FIELD)
private User leftChatMember; ///< Optional. A member was removed from the group, information about them (this member may be bot itself)
@JsonProperty(NEWCHATTITLE_FIELD)
private String newChatTitle; ///< Optional. A chat title was changed to this value
@JsonProperty(NEWCHATPHOTO_FIELD)
private List<PhotoSize> newChatPhoto; ///< Optional. A chat photo was change to this value
@JsonProperty(DELETECHATPHOTO_FIELD)
private Boolean deleteChatPhoto; ///< Optional. Informs that the chat photo was deleted
@JsonProperty(GROUPCHATCREATED_FIELD)
private Boolean groupchatCreated; ///< Optional. Informs that the group has been created
@JsonProperty(REPLYTOMESSAGE_FIELD)
private Message replyToMessage;
@JsonProperty(VOICE_FIELD)
private Voice voice; ///< Optional. Message is a voice message, information about the file
@JsonProperty(CAPTION_FIELD)
private String caption; ///< Optional. Caption for the document, photo or video, 0-200 characters
@JsonProperty(SUPERGROUPCREATED_FIELD)
private Boolean superGroupCreated;
@JsonProperty(CHANNELCHATCREATED_FIELD)
private Boolean channelChatCreated;
/**
* Optional. The group has been migrated to a supergroup with the specified identifier.
* This number may be greater than 32 bits and some programming languages
* may have difficulty/silent defects in interpreting it.
* But it smaller than 52 bits, so a signed 64 bit integer or double-precision
* float type are safe for storing this identifier.
*/
@JsonProperty(MIGRATETOCHAT_FIELD)
private Long migrateToChatId; ///< Optional. The chat has been migrated to a chat with specified identifier, not exceeding 1e13 by absolute value
/**
* Optional. The supergroup has been migrated from a group with the specified identifier.
* This number may be greater than 32 bits and some programming languages
* may have difficulty/silent defects in interpreting it.
* But it smaller than 52 bits, so a signed 64 bit integer or double-precision
* float type are safe for storing this identifier.
*/
@JsonProperty(MIGRATEFROMCHAT_FIELD)
private Long migrateFromChatId; ///< Optional. The chat has been migrated from a chat with specified identifier, not exceeding 1e13 by absolute value
@JsonProperty(EDITDATE_FIELD)
private Integer editDate; ///< Optional. Date the message was last edited in Unix time
@JsonProperty(GAME_FIELD)
private Game game; ///< Optional. Message is a game, information about the game
@JsonProperty(FORWARDFROMMESSAGEID_FIELD)
private Integer forwardFromMessageId; ///< Optional. For forwarded channel posts, identifier of the original message in the channel
@JsonProperty(INVOICE_FIELD)
private Invoice invoice; ///< Optional. Message is an invoice for a payment, information about the invoice.
@JsonProperty(SUCCESSFUL_PAYMENT_FIELD)
private SuccessfulPayment successfulPayment; ///< Optional. Message is a service message about a successful payment, information about the payment.
@JsonProperty(VIDEO_NOTE_FIELD)
private VideoNote videoNote; ///< Optional. Message is a video note, information about the video message
@JsonProperty(AUTHORSIGNATURE_FIELD)
private String authorSignature; ///< Optional. Post author signature for posts in channel chats
@JsonProperty(FORWARDSIGNATURE_FIELD)
private String forwardSignature; ///< Optional. Post author signature for messages forwarded from channel chats
@JsonProperty(MEDIAGROUPID_FIELD)
private String mediaGroupId; ///< Optional. The unique identifier of a media message group this message belongs to
@JsonProperty(CONNECTEDWEBSITE_FIELD)
private String connectedWebsite; ///< Optional. The domain name of the website on which the user has logged in
@JsonProperty(PASSPORTDATA_FIELD)
private PassportData passportData; ///< Optional. Telegram Passport data
public Message() {
super();
}
public Integer getMessageId() {
return messageId;
}
public User getFrom() {
return from;
}
public Integer getDate() {
return date;
}
public Chat getChat() {
return chat;
}
public User getForwardFrom() {
return forwardFrom;
}
public Integer getForwardDate() {
return forwardDate;
}
public String getText() {
return text;
}
public List<MessageEntity> getEntities() {
if (entities != null) {
entities.forEach(x -> x.computeText(text));
}
return entities;
}
public List<MessageEntity> getCaptionEntities() {
if (captionEntities != null) {
captionEntities.forEach(x -> x.computeText(caption));
}
return captionEntities;
}
public Audio getAudio() {
return audio;
}
public Document getDocument() {
return document;
}
public List<PhotoSize> getPhoto() {
return photo;
}
public Sticker getSticker() {
return sticker;
}
public boolean hasSticker() {
return sticker != null;
}
public Video getVideo() {
return video;
}
public Animation getAnimation() {
return animation;
}
public Contact getContact() {
return contact;
}
public Location getLocation() {
return location;
}
public Venue getVenue() {
return venue;
}
public Message getPinnedMessage() {
return pinnedMessage;
}
public List<User> getNewChatMembers() {
return newChatMembers == null ? new ArrayList<>() : newChatMembers;
}
public User getLeftChatMember() {
return leftChatMember;
}
public String getNewChatTitle() {
return newChatTitle;
}
public List<PhotoSize> getNewChatPhoto() {
return newChatPhoto;
}
public Boolean getDeleteChatPhoto() {
return deleteChatPhoto;
}
public Boolean getGroupchatCreated() {
return groupchatCreated;
}
public Message getReplyToMessage() {
return replyToMessage;
}
public Voice getVoice() {
return voice;
}
public String getCaption() {
return caption;
}
public Boolean getSuperGroupCreated() {
return superGroupCreated;
}
public Boolean getChannelChatCreated() {
return channelChatCreated;
}
public Long getMigrateToChatId() {
return migrateToChatId;
}
public Long getMigrateFromChatId() {
return migrateFromChatId;
}
public Integer getForwardFromMessageId() {
return forwardFromMessageId;
}
public boolean isGroupMessage() {
return chat.isGroupChat();
}
public boolean isUserMessage() {
return chat.isUserChat();
}
public boolean isChannelMessage() {
return chat.isChannelChat();
}
public boolean isSuperGroupMessage() {
return chat.isSuperGroupChat();
}
public Long getChatId() {
return chat.getId();
}
public boolean hasText() {
return text != null && !text.isEmpty();
}
public boolean isCommand() {
if (hasText() && entities != null) {
for (MessageEntity entity : entities) {
if (entity != null && entity.getOffset() == 0 &&
EntityType.BOTCOMMAND.equals(entity.getType())) {
return true;
}
}
}
return false;
}
public boolean hasDocument() {
return this.document != null;
}
public boolean hasVideo() {
return this.video != null;
}
public boolean hasAudio(){
return this.audio != null;
}
public boolean hasVoice(){
return this.voice != null;
}
public boolean isReply() {
return this.replyToMessage != null;
}
public boolean hasLocation() {
return location != null;
}
public Chat getForwardFromChat() {
return forwardFromChat;
}
public Integer getEditDate() {
return editDate;
}
public Game getGame() {
return game;
}
private boolean hasGame() {
return game != null;
}
public boolean hasEntities() {
return entities != null && !entities.isEmpty();
}
public boolean hasPhoto() {
return photo != null && !photo.isEmpty();
}
public boolean hasInvoice() {
return invoice != null;
}
public boolean hasSuccessfulPayment() {
return successfulPayment != null;
}
public boolean hasContact() {
return contact != null;
}
public Invoice getInvoice() {
return invoice;
}
public SuccessfulPayment getSuccessfulPayment() {
return successfulPayment;
}
public VideoNote getVideoNote() {
return videoNote;
}
public boolean hasVideoNote() {
return videoNote != null;
}
public String getAuthorSignature() {
return authorSignature;
}
public String getForwardSignature() {
return forwardSignature;
}
public String getMediaGroupId() {
return mediaGroupId;
}
public String getConnectedWebsite() {
return connectedWebsite;
}
public PassportData getPassportData() {
return passportData;
}
public boolean hasPassportData() {
return passportData != null;
}
public boolean hasAnimation() {
return animation != null;
}
@Override
public String toString() {
return "Message{" +
"messageId=" + messageId +
", from=" + from +
", date=" + date +
", chat=" + chat +
", forwardFrom=" + forwardFrom +
", forwardFromChat=" + forwardFromChat +
", forwardDate=" + forwardDate +
", text='" + text + '\'' +
", entities=" + entities +
", captionEntities=" + captionEntities +
", audio=" + audio +
", document=" + document +
", photo=" + photo +
", sticker=" + sticker +
", video=" + video +
", contact=" + contact +
", location=" + location +
", venue=" + venue +
", pinnedMessage=" + pinnedMessage +
", newChatMembers=" + newChatMembers +
", leftChatMember=" + leftChatMember +
", newChatTitle='" + newChatTitle + '\'' +
", newChatPhoto=" + newChatPhoto +
", deleteChatPhoto=" + deleteChatPhoto +
", groupchatCreated=" + groupchatCreated +
", replyToMessage=" + replyToMessage +
", voice=" + voice +
", caption='" + caption + '\'' +
", superGroupCreated=" + superGroupCreated +
", channelChatCreated=" + channelChatCreated +
", migrateToChatId=" + migrateToChatId +
", migrateFromChatId=" + migrateFromChatId +
", editDate=" + editDate +
", game=" + game +
", forwardFromMessageId=" + forwardFromMessageId +
", invoice=" + invoice +
", successfulPayment=" + successfulPayment +
", videoNote=" + videoNote +
", authorSignature='" + authorSignature + '\'' +
", forwardSignature='" + forwardSignature + '\'' +
", mediaGroupId='" + mediaGroupId + '\'' +
", connectedWebsite='" + connectedWebsite + '\'' +
", passportData=" + passportData +
'}';
}
}
|
// TODO : les todos
package client;
import java.net.MalformedURLException;
import java.rmi.AlreadyBoundException;
import java.rmi.Naming;
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import java.rmi.server.UnicastRemoteObject;
import java.util.UUID;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Set;
import commun.ClientInfo;
import commun.DejaConnecteException;
import commun.IClient;
import commun.IHotelDesVentes;
import commun.Objet;
import commun.PasCreateurException;
import commun.PseudoDejaUtiliseException;
import commun.SalleDeVenteInfo;
import commun.ServeurInfo;
import commun.Message;
public class Client extends UnicastRemoteObject implements IClient {
private static final long serialVersionUID = 1L;
private String urlEtPortServeur;
private String adresseServeur;
public ServeurInfo serveur;
public String getAdresseClient() {
return myClientInfos.getAdresseClient();
}
private IHotelDesVentes hdv=null;
private HashMap<UUID, Objet> ventesSuivies;
private HashMap<UUID, SalleDeVenteInfo> mapInfosSalles;
private HashMap<UUID, List<Message>> listesMessages;
public ClientInfo myClientInfos;
private UUID idSalleObservee;
private String nomSalleObservee;
private UUID idObjetObserve;
private String nomObjetObserve;
public void setIdSalleObservee(UUID idSalleObservee) {
this.idSalleObservee = idSalleObservee;
}
public Client(String nom,String ipServeurSaisi, String portServeurSaisi) throws RemoteException {
super();
this.myClientInfos = new ClientInfo(UUID.randomUUID(),nom, "127.0.0.1", "8092");
serveur= new ServeurInfo(ipServeurSaisi,portServeurSaisi);
d(serveur.getAdresseServeur());
connexionServeur();
this.ventesSuivies = new HashMap<UUID, Objet>();
}
public void connexionServeur() {
d("Tentative d'initialisation de hdv à l'adresse:"+serveur.getAdresseServeur());
while(hdv==null) {
try {
hdv = (IHotelDesVentes) Naming.lookup(serveur.getAdresseServeur());
System.out.println("Connexion au serveur " + serveur.getAdresseServeur() + " reussi.");
} catch (Exception e) {
System.out.println("Connexion au serveur " + serveur.getAdresseServeur() + " impossible.");
}
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public void connexion () {
try {
mapInfosSalles = hdv.login(this.myClientInfos);
} catch (RemoteException | PseudoDejaUtiliseException | DejaConnecteException e) {
e.printStackTrace();
}
}
public void deconnexion () {
try {
hdv.logout(myClientInfos);
} catch (RemoteException e) {
e.printStackTrace();
}
// TODO : fermeture de l'application ?
}
public void nouvelleSoumission(String nom, String description, int prix, UUID idSdv) throws RemoteException {
Objet nouveau = new Objet(nom, description, prix,myClientInfos.getNom());
//ajout de l'objet par le hdv
try {
hdv.ajouterObjet(nouveau, idSdv, getId());
} catch (PasCreateurException e) {
e.printStackTrace();
}
//print des informations sur l'ajout
}
public void nouvelleSalle(String nom, String description, float f) throws RemoteException {
Objet nouveau = new Objet(nom, description, f,myClientInfos.getNom());
System.out.println(""+myClientInfos.getAdresseClient()+" "+myClientInfos.getNom()+" "+getId()+" "+nouveau+" "+myClientInfos.getNom()+" \n");
hdv.creerSalle(myClientInfos, nouveau, "Salle de "+myClientInfos.getNom());
}
public void pingServeur() throws RemoteException {
if ( hdv==null) System.out.print("Hdv null : connexion pas effectué\n");
hdv.ping();
}
public static void main(String[] argv) {
try {
//start IHM
} catch (Exception e) {
e.printStackTrace();
}
}
public IHotelDesVentes getServeur() {
return hdv;
}
public void setServeur(IHotelDesVentes serveur) {
this.hdv = serveur;
}
// notification au serveur de la fermeture d'une salle par le client
public void fermetureSalle(UUID idSDV) {
try {
hdv.fermerSalle(idSDV, getId());
} catch (PasCreateurException e) {
e.printStackTrace();
} catch (RemoteException e) {
e.printStackTrace();
}
}
public void rejoindreSalle(UUID idSalle) {
try {
Objet obj = hdv.rejoindreSalle(idSalle, this.myClientInfos);
ventesSuivies.put(idSalle, obj);
// TODO : refresh l'IHM pour prendre en compte les modifs
} catch (RemoteException e) {
e.printStackTrace();
// TODO : affichage d'un message d'erreur par l'IHM
}
}
public HashMap<UUID, Objet> getVentesSuivies() {
return ventesSuivies;
}
@Override
public void nouveauMessage(UUID idSalle, Message message) {
listesMessages.get(idSalle).add(message);
// TODO : refresh l'IHM pour prendre en compte les modifs
}
@Override
public void notifModifObjet(UUID idSalle, Objet objet) {
ventesSuivies.put(idSalle, objet);
mapInfosSalles.get(idSalle).setObjCourrant(objet);
// TODO : refresh l'IHM pour prendre en compte les modifs
}
@Override
public void notifFermetureSalle(UUID idSalle) {
ventesSuivies.remove(idSalle);
mapInfosSalles.remove(idSalle);
// TODO : refresh l'IHM pour prendre en compte les modifs
}
@Override
public void notifNouvelleSalle(UUID idsdv, SalleDeVenteInfo sdvi) {
mapInfosSalles.put(idsdv, sdvi);
}
public UUID getIdSalleObservee() {
return this.idSalleObservee;
}
public HashMap<UUID, SalleDeVenteInfo> getMapInfosSalles() {
return mapInfosSalles;
}
public void setMapInfosSalles(HashMap<UUID, SalleDeVenteInfo> mapInfosSalles) {
this.mapInfosSalles = mapInfosSalles;
}
public SalleDeVenteInfo[] getTabInfosSalles() {
if (mapInfosSalles != null) {
Collection<SalleDeVenteInfo> vals = mapInfosSalles.values();
SalleDeVenteInfo[] tab = new SalleDeVenteInfo[vals.size()];
int i = 0;
for (SalleDeVenteInfo sdvi : vals) {
tab[i] = sdvi;
++i;
}
return tab;
}
// TODO : lever une exception ?
else return new SalleDeVenteInfo[0];
}
public SalleDeVenteInfo[] getTabVentesSuivies() {
if (ventesSuivies != null) {
Set<UUID> keys = ventesSuivies.keySet();
SalleDeVenteInfo[] tab = new SalleDeVenteInfo[keys.size()];
int i = 0;
for (UUID idSalle : keys) {
tab[i] = mapInfosSalles.get(idSalle);
++i;
}
return tab;
}
// TODO : lever une exception ?
else return new SalleDeVenteInfo[0];
}
public void quitterSalle(UUID idSalleAQuitter) {
try {
hdv.quitterSalle( getId(),idSalleAQuitter);
} catch (RemoteException e) {
e.printStackTrace();
}
}
public UUID getId() {
return myClientInfos.getId();
}
public String getPortClient() {
return myClientInfos.getPort();
}
public void setPortClient(String portClient) {
myClientInfos.setPort(portClient);
}
public void bindClient() {
Boolean flagRegistreOkay=false;
while(!flagRegistreOkay) {
try {
Registry r = LocateRegistry.getRegistry(Integer.parseInt(serveur.getPort()));
if (r==null) {
r=LocateRegistry.createRegistry(Integer.parseInt(serveur.getPort()));
d("Registre créé au port "+serveur.getPort());
}else {
d("Registre trouvé au port "+serveur.getPort());
}
flagRegistreOkay=true;
} catch (NumberFormatException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (RemoteException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
setPortClient( Integer.toString(Integer.parseInt(getPortClient())+1) );
}
d("Tentative de bind à "+getAdresseClient());
try {
Naming.bind(getAdresseClient(), this);
} catch(AlreadyBoundException alreadyBoundException) {
d("LOL:AlreadyBound");
} catch (MalformedURLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (RemoteException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
d("bind effectué");
}
public static void d(String msg) {
System.out.println(msg+"\n");
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.