answer
stringlengths
17
10.2M
package ru.r2cloud.it; import static org.junit.Assert.assertEquals; import java.net.http.HttpResponse; import java.util.UUID; import org.junit.Test; import com.eclipsesource.json.JsonObject; import ru.r2cloud.it.util.RegisteredTest; import ru.r2cloud.model.GeneralConfiguration; public class GeneralConfigurationTest extends RegisteredTest { @Test public void testConfiguration() { GeneralConfiguration config = createConfig(); client.setGeneralConfiguration(config); JsonObject configuration = client.getGeneralConfiguration(); assertEquals(config.getLat(), configuration.getDouble("lat", 0.0), 0.0); assertEquals(config.getLng(), configuration.getDouble("lng", 0.0), 0.0); assertEquals(config.isAutoUpdate(), configuration.getBoolean("autoUpdate", !config.isAutoUpdate())); assertEquals(config.getPpm().intValue(), configuration.getInt("ppm", -1)); assertEquals(config.getElevationMin(), configuration.getDouble("elevationMin", 0.0), 0.0); assertEquals(config.getElevationGuaranteed(), configuration.getDouble("elevationGuaranteed", 0.0), 0.0); assertEquals(config.isRotationEnabled(), configuration.getBoolean("rotationEnabled", false)); assertEquals(config.getRotctrldHostname(), configuration.getString("rotctrldHostname", null)); assertEquals(config.getRotctrldPort().intValue(), configuration.getInt("rotctrldPort", 0)); assertEquals(config.getRotatorTolerance(), configuration.getDouble("rotatorTolerance", 0.0), 0.0); assertEquals(config.getRotatorCycle().longValue(), configuration.getLong("rotatorCycle", 0)); assertEquals(config.getGain().doubleValue(), configuration.getDouble("gain", 0.0), 0.0); assertEquals(config.isBiast(), configuration.getBoolean("biast", false)); } @Test public void testInvalidGain() { GeneralConfiguration config = createConfig(); config.setGain(null); HttpResponse<String> response = client.setGeneralConfigurationWithResponse(config); assertEquals(400, response.statusCode()); assertErrorInField("gain", response); config = createConfig(); config.setGain(-1.0); response = client.setGeneralConfigurationWithResponse(config); assertEquals(400, response.statusCode()); assertErrorInField("gain", response); config = createConfig(); config.setGain(51.0); response = client.setGeneralConfigurationWithResponse(config); assertEquals(400, response.statusCode()); assertErrorInField("gain", response); } @Test public void testInvalidElevationMin() { GeneralConfiguration config = createConfig(); config.setElevationMin(null); HttpResponse<String> response = client.setGeneralConfigurationWithResponse(config); assertEquals(400, response.statusCode()); assertErrorInField("elevationMin", response); config = createConfig(); config.setElevationMin(-1.0); response = client.setGeneralConfigurationWithResponse(config); assertEquals(400, response.statusCode()); assertErrorInField("elevationMin", response); config = createConfig(); config.setElevationMin(10.0); config.setElevationGuaranteed(5.0); response = client.setGeneralConfigurationWithResponse(config); assertEquals(400, response.statusCode()); assertErrorInField("elevationMin", response); } @Test public void testInvalidElevationGuaranteed() { GeneralConfiguration config = createConfig(); config.setElevationGuaranteed(null); HttpResponse<String> response = client.setGeneralConfigurationWithResponse(config); assertEquals(400, response.statusCode()); assertErrorInField("elevationGuaranteed", response); config = createConfig(); config.setElevationGuaranteed(91.0); response = client.setGeneralConfigurationWithResponse(config); assertEquals(400, response.statusCode()); assertErrorInField("elevationGuaranteed", response); } @Test public void testRotctldConfiguration() { GeneralConfiguration config = createConfig(); config.setRotctrldHostname(null); HttpResponse<String> response = client.setGeneralConfigurationWithResponse(config); assertEquals(400, response.statusCode()); assertErrorInField("rotctrldHostname", response); config = createConfig(); config.setRotctrldHostname(UUID.randomUUID().toString()); response = client.setGeneralConfigurationWithResponse(config); assertEquals(400, response.statusCode()); assertErrorInField("rotctrldHostname", response); config = createConfig(); config.setRotctrldPort(null); response = client.setGeneralConfigurationWithResponse(config); assertEquals(400, response.statusCode()); assertErrorInField("rotctrldPort", response); config = createConfig(); config.setRotatorTolerance(null); response = client.setGeneralConfigurationWithResponse(config); assertEquals(400, response.statusCode()); assertErrorInField("rotatorTolerance", response); config = createConfig(); config.setRotatorCycle(null); response = client.setGeneralConfigurationWithResponse(config); assertEquals(400, response.statusCode()); assertErrorInField("rotatorCycle", response); } @Test public void testInvalidLat() { GeneralConfiguration config = createConfig(); config.setLat(null); HttpResponse<String> response = client.setGeneralConfigurationWithResponse(config); assertEquals(400, response.statusCode()); assertErrorInField("lat", response); } @Test public void testInvalidLng() { GeneralConfiguration config = createConfig(); config.setLng(null); HttpResponse<String> response = client.setGeneralConfigurationWithResponse(config); assertEquals(400, response.statusCode()); assertErrorInField("lng", response); } private static GeneralConfiguration createConfig() { GeneralConfiguration config = new GeneralConfiguration(); config.setLat(10.1); config.setLng(23.4); config.setAutoUpdate(true); config.setPpm(10); config.setElevationMin(8d); config.setElevationGuaranteed(20d); config.setRotationEnabled(true); config.setRotctrldHostname("127.0.0.1"); config.setRotctrldPort(4533); config.setRotatorTolerance(5.1); config.setRotatorCycle(1000L); config.setGain(44.5); config.setBiast(false); return config; } }
package com.example.bewegungsmeldermain; import android.app.Service; import android.content.Intent; import android.hardware.Sensor; import android.hardware.SensorEvent; import android.hardware.SensorEventListener; import android.hardware.SensorManager; import android.os.IBinder; import android.util.Log; import android.widget.Toast; public class MotionDetectionService extends Service implements SensorEventListener{ private static final String TAG = MotionDetectionService.class.getSimpleName(); private SensorManager mSensorManager; private Sensor mAccelerometer; // Wird fuer IPC benoetigt (inter-process communication") @Override public IBinder onBind(Intent intent) { // TODO Auto-generated method stub return null; } @Override public void onCreate() { Log.d(TAG, "created"); // System Service zuweisen mSensorManager = (SensorManager)getSystemService(SENSOR_SERVICE); mAccelerometer = mSensorManager.getDefaultSensor(Sensor.TYPE_GYROSCOPE); super.onCreate(); } @Override public void onDestroy() { Log.d(TAG, "destroyed"); super.onDestroy(); } /* * @see android.app.Service#onStart(android.content.Intent, int) */ @Override public void onStart(Intent intent, int startId) { // TODO Auto-generated method stub super.onStart(intent, startId); } @Override public void onAccuracyChanged(Sensor sensor, int accuracy) { // TODO Auto-generated method stub } @Override public void onSensorChanged(SensorEvent event) { Log.d(TAG, "Sensor changed"); //mSensorManager.getOrientation(R., values) } }
package com.asquera.elasticsearch.river.jruby; import java.util.Map; import java.util.List; import java.net.URL; import java.net.MalformedURLException; import java.io.File; import org.elasticsearch.ExceptionsHelper; import org.elasticsearch.action.ActionListener; import org.elasticsearch.action.bulk.BulkResponse; import org.elasticsearch.client.Client; import org.elasticsearch.client.Requests; import org.elasticsearch.client.action.bulk.BulkRequestBuilder; import org.elasticsearch.cluster.block.ClusterBlockException; import org.elasticsearch.common.Strings; import org.elasticsearch.common.inject.Inject; import org.elasticsearch.common.unit.TimeValue; import org.elasticsearch.common.xcontent.XContentBuilder; import org.elasticsearch.common.xcontent.XContentFactory; import org.elasticsearch.common.xcontent.support.XContentMapValues; import org.elasticsearch.indices.IndexAlreadyExistsException; import org.elasticsearch.river.AbstractRiverComponent; import org.elasticsearch.river.River; import org.elasticsearch.river.RiverName; import org.elasticsearch.river.RiverSettings; import org.elasticsearch.threadpool.ThreadPool; import org.jruby.Ruby; import org.jruby.RubyModule; import org.jruby.javasupport.JavaUtil; import org.jruby.RubyClass; import org.jruby.embed.ScriptingContainer; import org.jruby.embed.PathType; import org.jruby.embed.AttributeName; import org.jruby.javasupport.util.RuntimeHelpers; import org.jruby.runtime.builtin.IRubyObject; import org.jruby.runtime.ThreadContext; import org.jruby.runtime.GlobalVariable; import org.jruby.internal.runtime.GlobalVariables; import org.jruby.anno.JRubyMethod; import static org.jruby.runtime.Visibility.*; import static org.jruby.CompatVersion.*; import org.jruby.embed.LocalContextScope; /** * @author Florian Gilcher (florian.gilcher@asquera.de) */ public class JRubyRiver extends AbstractRiverComponent implements River { private ScriptingContainer container; private IRubyObject river; private Client client; private ThreadPool threadPool; @Inject public JRubyRiver(RiverName riverName, RiverSettings settings, Client client, ThreadPool threadPool) throws Exception { super(riverName, settings); this.client = client; this.threadPool = threadPool; this.container = new ScriptingContainer(LocalContextScope.SINGLETHREAD); Map <String, Object> riverSettings = (Map<String, Object>) settings.settings().get("jruby"); String scriptName = null; String scriptDirectory = null; if (null != riverSettings) { scriptName = XContentMapValues.nodeStringValue(riverSettings.get("script_name"), "scripts/" + riverName.name() + ".rb"); scriptDirectory = XContentMapValues.nodeStringValue(riverSettings.get("script_directory"), null); } else { scriptName = "scripts/" + riverName.name() + ".rb"; } if (null != scriptDirectory) { logger.info("changing to script directory [{}]", scriptDirectory); container.setAttribute(AttributeName.BASE_DIR, scriptDirectory); container.setCurrentDirectory(scriptDirectory); } Ruby runtime = setupRuntime(); logger.info("running script [{}]", scriptName); container.runScriptlet(PathType.RELATIVE, scriptName); logger.info("found river class [{}]", river(runtime)); RubyClass klass = river(runtime); this.river = RuntimeHelpers.invoke(runtime.getCurrentContext(), klass, "new"); } @Override public void start() { try { RuntimeHelpers.invoke(getRuntime().getCurrentContext(), this.river, "start"); } catch (Exception e) { logger.error("error in River#start [{}]", e); } } @Override public void close() { try { RuntimeHelpers.invoke(getRuntime().getCurrentContext(), this.river, "close"); } catch (Exception e) { logger.error("error in River#close [{}]", e); } } private Ruby setupRuntime() { Ruby runtime = getRuntime(); RubyModule kernel = runtime.getKernel(); kernel.defineAnnotatedMethods(KernelMethods.class); RubyModule river_settings = runtime.defineModule("RiverSettings"); river_settings.defineAnnotatedMethods(RiverSettingsModule.class); GlobalVariables vars = runtime.getGlobalVariables(); runtime.defineVariable(new GlobalVariable(runtime, "$river", runtime.getNil())); runtime.defineVariable(new GlobalVariable(runtime, "$client", JavaUtil.convertJavaToRuby(runtime, client))); runtime.defineVariable(new GlobalVariable(runtime, "$threadpool", JavaUtil.convertJavaToRuby(runtime, threadPool))); runtime.defineVariable(new GlobalVariable(runtime, "$settings", JavaUtil.convertJavaToRuby(runtime, settings))); runtime.defineVariable(new GlobalVariable(runtime, "$name", JavaUtil.convertJavaToRuby(runtime, riverName.name()))); runtime.defineVariable(new GlobalVariable(runtime, "$logger", JavaUtil.convertJavaToRuby(runtime, logger))); return runtime; } private Ruby getRuntime() { return container.getProvider().getRuntime(); } private RubyClass river(Ruby runtime) { return (RubyClass)runtime.getGlobalVariables().get("$river"); } }
package seedu.tasklist.commons.core; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; public class ConfigTest { @Rule public ExpectedException thrown = ExpectedException.none(); @Test public void toString_defaultObject_stringReturned() { String defaultConfigAsString = "App title : FlexiTask\n" + "Current log level : INFO\n" + "Preference file Location : preferences.json\n" + "Local data file location : data/tasklist.xml\n" + "TaskList name : MyTaskList"; assertEquals(defaultConfigAsString, new Config().toString()); } @Test public void equalsMethod() { Config defaultConfig = new Config(); assertNotNull(defaultConfig); assertTrue(defaultConfig.equals(defaultConfig)); Config config = new Config(); assertFalse(config.equals("MyTaskList")); } //@@author A0141993X @Test public void hashCodeMethod() { Config defaultConfig = new Config(); assertEquals(defaultConfig.hashCode(), defaultConfig.hashCode()); Config config = new Config(); assertEquals(config.hashCode(), defaultConfig.hashCode()); } }
package com.blackbuild.klum.common; import groovy.lang.Closure; import groovy.lang.DelegatesTo; import org.codehaus.groovy.ast.ASTNode; import org.codehaus.groovy.ast.AnnotationNode; import org.codehaus.groovy.ast.ClassHelper; import org.codehaus.groovy.ast.ClassNode; import org.codehaus.groovy.ast.FieldNode; import org.codehaus.groovy.ast.GenericsType; import org.codehaus.groovy.ast.MethodNode; import org.codehaus.groovy.ast.Parameter; import org.codehaus.groovy.ast.expr.ClosureExpression; import org.codehaus.groovy.ast.expr.Expression; import org.codehaus.groovy.ast.expr.MethodCallExpression; import org.codehaus.groovy.ast.stmt.BlockStatement; import org.codehaus.groovy.ast.stmt.ExpressionStatement; import org.codehaus.groovy.ast.stmt.ForStatement; import org.codehaus.groovy.ast.stmt.Statement; import org.codehaus.groovy.ast.tools.GeneralUtils; import org.codehaus.groovy.ast.tools.GenericsUtils; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import static org.codehaus.groovy.ast.ClassHelper.CLASS_Type; import static org.codehaus.groovy.ast.ClassHelper.make; import static org.codehaus.groovy.ast.tools.GeneralUtils.args; import static org.codehaus.groovy.ast.tools.GeneralUtils.block; import static org.codehaus.groovy.ast.tools.GeneralUtils.callX; import static org.codehaus.groovy.ast.tools.GeneralUtils.classX; import static org.codehaus.groovy.ast.tools.GeneralUtils.closureX; import static org.codehaus.groovy.ast.tools.GeneralUtils.constX; import static org.codehaus.groovy.ast.tools.GeneralUtils.propX; import static org.codehaus.groovy.ast.tools.GeneralUtils.returnS; import static org.codehaus.groovy.ast.tools.GeneralUtils.stmt; import static org.codehaus.groovy.ast.tools.GeneralUtils.varX; import static org.codehaus.groovy.ast.tools.GenericsUtils.buildWildcardType; import static org.codehaus.groovy.ast.tools.GenericsUtils.makeClassSafeWithGenerics; import static org.codehaus.groovy.ast.tools.GenericsUtils.nonGeneric; @SuppressWarnings("unchecked") public abstract class GenericsMethodBuilder<T extends GenericsMethodBuilder> { public static final ClassNode DEPRECATED_NODE = ClassHelper.make(Deprecated.class); private static final ClassNode[] EMPTY_EXCEPTIONS = new ClassNode[0]; private static final Parameter[] EMPTY_PARAMETERS = new Parameter[0]; private static final ClassNode DELEGATES_TO_ANNOTATION = make(DelegatesTo.class); private static final ClassNode DELEGATES_TO_TARGET_ANNOTATION = make(DelegatesTo.Target.class); protected String name; protected Map<Object, Object> metadata = new HashMap<Object, Object>(); private int modifiers; private ClassNode returnType = ClassHelper.VOID_TYPE; private List<ClassNode> exceptions = new ArrayList<ClassNode>(); private List<Parameter> parameters = new ArrayList<Parameter>(); private boolean deprecated; private BlockStatement body = new BlockStatement(); private boolean optional; private ASTNode sourceLinkTo; protected GenericsMethodBuilder(String name) { this.name = name; } @SuppressWarnings("ToArrayCallWithZeroLengthArrayArgument") public MethodNode addTo(ClassNode target) { Parameter[] parameterArray = this.parameters.toArray(EMPTY_PARAMETERS); MethodNode existing = target.getDeclaredMethod(name, parameterArray); if (existing != null) { if (optional) return existing; else throw new MethodBuilderException("Method " + existing + " is already defined.", existing); } MethodNode method = target.addMethod( name, modifiers, returnType, parameterArray, exceptions.toArray(EMPTY_EXCEPTIONS), body ); if (deprecated) method.addAnnotation(new AnnotationNode(DEPRECATED_NODE)); if (sourceLinkTo != null) method.setSourcePosition(sourceLinkTo); for (Map.Entry<Object, Object> entry : metadata.entrySet()) { method.putNodeMetaData(entry.getKey(), entry.getValue()); } return method; } public T optional() { this.optional = true; return (T)this; } public T returning(ClassNode returnType) { this.returnType = returnType; return (T)this; } public T mod(int modifier) { modifiers |= modifier; return (T)this; } public T param(Parameter param) { parameters.add(param); return (T)this; } public T deprecated() { deprecated = true; return (T)this; } public T namedParams(String name) { GenericsType wildcard = new GenericsType(ClassHelper.OBJECT_TYPE); wildcard.setWildcard(true); return param(makeClassSafeWithGenerics(ClassHelper.MAP_TYPE, new GenericsType(ClassHelper.STRING_TYPE), wildcard), name); } public T applyNamedParams(String parameterMapName) { statement( new ForStatement(new Parameter(ClassHelper.DYNAMIC_TYPE, "it"), callX(varX(parameterMapName), "entrySet"), new ExpressionStatement( new MethodCallExpression( varX("$rw"), "invokeMethod", args(propX(varX("it"), "key"), propX(varX("it"), "value")) ) ) ) ); return (T)this; } public T closureParam(String name) { param(GeneralUtils.param(GenericsUtils.nonGeneric(ClassHelper.CLOSURE_TYPE), name)); return (T)this; } public T delegationTargetClassParam(String name, ClassNode upperBound) { Parameter param = GeneralUtils.param(makeClassSafeWithGenerics(CLASS_Type, buildWildcardType(upperBound)), name); param.addAnnotation(new AnnotationNode(DELEGATES_TO_TARGET_ANNOTATION)); return param(param); } public T simpleClassParam(String name, ClassNode upperBound) { return param(makeClassSafeWithGenerics(CLASS_Type, buildWildcardType(upperBound)), name); } public T stringParam(String name) { return param(ClassHelper.STRING_TYPE, name); } public T optionalStringParam(String name, Object addIfNotNull) { if (addIfNotNull != null) stringParam(name); return (T)this; } public T objectParam(String name) { return param(ClassHelper.OBJECT_TYPE, name); } public T param(ClassNode type, String name) { return param(new Parameter(type, name)); } public T param(ClassNode type, String name, Expression defaultValue) { return param(new Parameter(type, name, defaultValue)); } public T arrayParam(ClassNode type, String name) { return param(new Parameter(type.makeArray(), name)); } public T cloneParamsFrom(MethodNode methods) { Parameter[] sourceParams = GeneralUtils.cloneParams(methods.getParameters()); for (Parameter parameter : sourceParams) { param(parameter); } return (T)this; } public T withMetadata(Object key, Object value) { metadata.put(key, value); return (T)this; } public T delegatingClosureParam(ClassNode delegationTarget, ClosureDefaultValue defaultValue) { return delegatingClosureParam(delegationTarget, defaultValue, Closure.DELEGATE_ONLY); } public T passThroughClosureParam(ClassNode delegationTarget, ClosureDefaultValue defaultValue) { return delegatingClosureParam(delegationTarget, defaultValue, Closure.OWNER_ONLY); } public T delegatingClosureParam(ClassNode delegationTarget, ClosureDefaultValue defaultValue, int delegationStrategy) { ClosureExpression emptyClosure = null; if (defaultValue == ClosureDefaultValue.EMPTY_CLOSURE) { emptyClosure = closureX(block()); } Parameter param = GeneralUtils.param( nonGeneric(ClassHelper.CLOSURE_TYPE), "closure", emptyClosure ); param.addAnnotation(createDelegatesToAnnotation(delegationTarget, delegationStrategy)); return param(param); } public T delegatingClosureParam() { return delegatingClosureParam(null, ClosureDefaultValue.EMPTY_CLOSURE); } public AnnotationNode createDelegatesToAnnotation(ClassNode target, int strategy) { AnnotationNode annotation = new AnnotationNode(DELEGATES_TO_ANNOTATION); if (target != null) annotation.setMember("value", classX(target)); else annotation.setMember("genericTypeIndex", constX(0)); annotation.setMember("strategy", constX(strategy)); return annotation; } public T statement(Statement statement) { body.addStatement(statement); return (T)this; } public T statementIf(boolean condition, Statement statement) { if (condition) body.addStatement(statement); return (T)this; } public T assignToProperty(String propertyName, Expression value) { String[] split = propertyName.split("\\.", 2); if (split.length == 1) return assignS(propX(varX("this"), propertyName), value); return assignS(propX(varX(split[0]), split[1]), value); } public T assignS(Expression target, Expression value) { return statement(GeneralUtils.assignS(target, value)); } public T optionalAssignPropertyFromPropertyS(String target, String targetProperty, String value, String valueProperty, Object marker) { if (marker != null) assignS(propX(varX(target), targetProperty), propX(varX(value), valueProperty)); return (T)this; } public T declareVariable(String varName, Expression init) { return statement(GeneralUtils.declS(varX(varName), init)); } public T callMethod(Expression receiver, String methodName) { return callMethod(receiver, methodName, MethodCallExpression.NO_ARGUMENTS); } public T callMethod(String receiverName, String methodName) { return callMethod(varX(receiverName), methodName); } public T callMethod(Expression receiver, String methodName, Expression args) { return statement(callX(receiver, methodName, args)); } public T callMethod(String receiverName, String methodName, Expression args) { return callMethod(varX(receiverName), methodName, args); } public T callThis(String methodName, Expression args) { return callMethod("this", methodName, args); } public T callThis(String methodName) { return callMethod("this", methodName); } @Deprecated public T println(Expression args) { return callThis("println", args); } @Deprecated public T println(String string) { return callThis("println", constX(string)); } public T statement(Expression expression) { return statement(stmt(expression)); } public T statementIf(boolean condition, Expression expression) { return statementIf(condition, stmt(expression)); } public T doReturn(String varName) { return doReturn(varX(varName)); } public T doReturn(Expression expression) { return statement(returnS(expression)); } public T linkToField(FieldNode fieldNode) { return (T) inheritDeprecationFrom(fieldNode).sourceLinkTo(fieldNode); } public T inheritDeprecationFrom(FieldNode fieldNode) { if (!fieldNode.getAnnotations(DEPRECATED_NODE).isEmpty()) { deprecated = true; } return (T)this; } public T sourceLinkTo(ASTNode sourceLinkTo) { this.sourceLinkTo = sourceLinkTo; return (T)this; } public enum ClosureDefaultValue { NONE, EMPTY_CLOSURE } }
package com.gracecode.android.rain.ui.fragment; import android.content.BroadcastReceiver; import android.content.Intent; import android.content.IntentFilter; import android.content.SharedPreferences; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.ListView; import android.widget.Toast; import com.gracecode.android.rain.R; import com.gracecode.android.rain.Rainville; import com.gracecode.android.rain.adapter.PresetsAdapter; import com.gracecode.android.rain.helper.MixerPresetsHelper; import com.gracecode.android.rain.helper.SendBroadcastHelper; import com.gracecode.android.rain.receiver.PlayBroadcastReceiver; import com.gracecode.android.rain.serivce.PlayService; import com.umeng.analytics.MobclickAgent; public class PresetsFragment extends PlayerFragment implements MixerPresetsHelper, AdapterView.OnItemClickListener { public static final String PREF_SAVED_PRESET_NAME = "pref_saved_preset_name"; private PresetsAdapter mAdapter; private SharedPreferences mSharedPreferences; private ListView mListView; private boolean isDisabled = false; private String[] mPresets; private BroadcastReceiver mBroadcastReceiver = new PlayBroadcastReceiver() { @Override public void onPlay() { setPlaying(); } @Override public void onStop() { setStopped(); } @Override public void onSetVolume(int track, int volume) { } @Override public void onSetPresets(float[] presets) { // savePresets(presets); } @Override public void onHeadsetPlugged() { setDisabled(false); } @Override public void onHeadsetUnPlugged() { setDisabled(true); } }; public void setDisabled(boolean flag) { this.isDisabled = flag; } @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); mPresets = getResources().getStringArray(R.array.presets); mAdapter = new PresetsAdapter(getActivity(), mPresets); mSharedPreferences = Rainville.getInstance().getSharedPreferences(); String preset = mSharedPreferences.getString(PREF_SAVED_PRESET_NAME, mPresets[0]); mAdapter.setCurrentPresetName(preset); SendPresetsBroadcast(preset); } private void SendPresetsBroadcast(String name) { int position = mAdapter.getPositionFromName(name); SendPresetsBroadcast(position); } private void SendPresetsBroadcast(int position) { try { SendBroadcastHelper.sendPresetsBroadcast(getActivity(), getPresetsFromPosition(position)); } catch (RuntimeException e) { e.printStackTrace(); } } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_persents, null); mListView = (ListView) view.findViewById(android.R.id.list); return view; } @Override public void onStart() { super.onStart(); mListView.setAdapter(mAdapter); mListView.setOnItemClickListener(this); IntentFilter filter = new IntentFilter(); for (String action : new String[]{ Intent.ACTION_HEADSET_PLUG, PlayBroadcastReceiver.PLAY_BROADCAST_NAME, PlayService.ACTION_A2DP_HEADSET_PLUG }) { filter.addAction(action); } getActivity().registerReceiver(mBroadcastReceiver, filter); setDisabled(true); } @Override public void onStop() { super.onStop(); getActivity().unregisterReceiver(mBroadcastReceiver); } private float[] getPresetsFromPosition(int position) { return ALL_PRESETS[position]; } @Override public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) { if (isDisabled) { Toast.makeText(getActivity(), getString(R.string.headset_needed), Toast.LENGTH_SHORT).show(); return; } String presetName = mAdapter.getItem(i); SendPresetsBroadcast(i); if (!isPlaying()) { SendBroadcastHelper.sendPlayBroadcast(getActivity()); } SharedPreferences.Editor editor = mSharedPreferences.edit(); editor.putString(PREF_SAVED_PRESET_NAME, presetName); editor.commit(); if (!presetName.equals(mAdapter.getCurrentPreset())) { mAdapter.setCurrentPresetName(presetName); mAdapter.notifyDataSetChanged(); } //UIHelper.showShortToast(getActivity(), presetName); MobclickAgent.onEvent(getActivity(), presetName); } }
package com.ciandt.techgallery.service; import com.google.api.server.spi.response.BadRequestException; import com.google.api.server.spi.response.InternalServerErrorException; import com.google.api.server.spi.response.NotFoundException; import com.google.appengine.api.users.User; import com.ciandt.techgallery.persistence.model.Technology; import com.ciandt.techgallery.service.model.Response; import com.ciandt.techgallery.service.model.TechnologyFilter; import com.ciandt.techgallery.service.model.TechnologyResponse; import java.util.List; /** * Services for Technologies. * * @author felipers * */ public interface TechnologyService { /** * Service for adding a technology. * * @param technology json with technology info. * @return technology info or message error. * @throws InternalServerErrorException * @throws BadRequestException */ public Response addTechnology(final TechnologyResponse technology) throws InternalServerErrorException, BadRequestException; /** * Service for getting all technologies. * * @return technologies info or message error. * @throws InternalServerErrorException * @throws NotFoundException */ Response getTechnologies() throws InternalServerErrorException, NotFoundException; /** * Service for getting a technology response. * * @param id entity id. * @return . * @throws NotFoundException . */ Response getTechnology(final String id) throws NotFoundException; /** * Service for getting all technologies according a filter. * * @param filter entity filter. * @return technologies info or message error. * @throws InternalServerErrorException . * @throws NotFoundException . */ Response findTechnologiesByFilter(final TechnologyFilter techFilter, User user) throws InternalServerErrorException, NotFoundException, BadRequestException; /** * Service for getting a technology * * @param id entity id * @return . * @throws NotFoundException when entity is not found */ Technology getTechnologyById(String id) throws NotFoundException; List<String> getOrderOptions(User user); }
package nu.validator.checker; import org.xml.sax.Attributes; import org.xml.sax.SAXException; public class UnsupportedFeatureChecker extends Checker { /** * @see nu.validator.checker.Checker#startElement(java.lang.String, * java.lang.String, java.lang.String, org.xml.sax.Attributes) */ @Override public void startElement(String uri, String localName, String qName, Attributes atts) throws SAXException { if ("http: return; } if (atts.getIndex("", "contextmenu") > -1) { warnAboutAttribute("contextmenu"); } if (atts.getIndex("", "dropzone") > -1) { warnAboutAttribute("dropzone"); } if ("dialog" == localName || "bdi" == localName) { warnAboutElement(localName); } else if ("textarea" == localName) { if (atts.getIndex("", "dirname") > -1) { warnAboutAttributeOnElement("dirname", "textarea"); } if (atts.getIndex("", "inputmode") > -1) { warnAboutAttribute("inputmode"); } } else if ("menu" == localName) { if (atts.getIndex("", "type") > -1 && AttributeUtil.lowerCaseLiteralEqualsIgnoreAsciiCaseString( "context", atts.getValue("", "type"))) { warn("Context menus are not supported in all browsers." + " Please be sure to test, and consider using a polyfill."); } } else if ("script" == localName) { if (atts.getIndex("", "type") > -1 && AttributeUtil.lowerCaseLiteralEqualsIgnoreAsciiCaseString( "module", atts.getValue("", "type"))) { warn("Module scripts are not supported in most browsers yet."); } } else if ("input" == localName) { if (atts.getIndex("", "dirname") > -1) { warnAboutAttributeOnElement("dirname", "input"); } if (atts.getIndex("", "inputmode") > -1) { warnAboutAttribute("inputmode"); } String type = atts.getValue("", "type"); if (AttributeUtil.lowerCaseLiteralEqualsIgnoreAsciiCaseString( "date", type)) { warnAboutInputType("date"); } else if (AttributeUtil.lowerCaseLiteralEqualsIgnoreAsciiCaseString( "month", type)) { warnAboutInputType("month"); } else if (AttributeUtil.lowerCaseLiteralEqualsIgnoreAsciiCaseString( "week", type)) { warnAboutInputType("week"); } else if (AttributeUtil.lowerCaseLiteralEqualsIgnoreAsciiCaseString( "time", type)) { warnAboutInputType("time"); } else if (AttributeUtil.lowerCaseLiteralEqualsIgnoreAsciiCaseString( "datetime-local", type)) { warnAboutInputType("datetime-local"); } else if (AttributeUtil.lowerCaseLiteralEqualsIgnoreAsciiCaseString( "color", type)) { warnAboutInputType("color"); } } } private void warnAboutInputType(String name) throws SAXException { warn("The \u201C" + name + "\u201D input type is not supported in" + " all browsers. Please be sure to test, and consider" + " using a polyfill."); } private void warnAboutAttribute(String name) throws SAXException { warn("The \u201C" + name + "\u201D attribute is not supported in" + " all browsers. Please be sure to test, and consider" + " using a polyfill."); } private void warnAboutElement(String name) throws SAXException { warn("The \u201C" + name + "\u201D element is not supported in" + " all browsers. Please be sure to test, and consider" + " using a polyfill."); } private void warnAboutAttributeOnElement(String attributeName, String elementName) throws SAXException { warn("The \u201C" + attributeName + "\u201D attribute on the" + " \u201C" + elementName + "\u201D element is not supported" + " in all browsers. Please be sure to test, and consider" + " using a polyfill."); } }
package com.cloudbees.jenkins.plugins.amazonecs; import java.io.IOException; import java.text.MessageFormat; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Date; import java.util.List; import java.util.concurrent.Callable; import java.util.logging.Level; import java.util.logging.Logger; import javax.annotation.CheckForNull; import javax.annotation.Nonnull; import javax.annotation.Nullable; import javax.servlet.ServletException; import org.apache.commons.lang.StringUtils; import org.kohsuke.stapler.DataBoundConstructor; import org.kohsuke.stapler.DataBoundSetter; import org.kohsuke.stapler.QueryParameter; import com.amazonaws.AmazonClientException; import com.amazonaws.regions.Region; import com.amazonaws.regions.RegionUtils; import com.amazonaws.regions.Regions; import com.amazonaws.services.ecs.AmazonECSClient; import com.cloudbees.jenkins.plugins.awscredentials.AWSCredentialsHelper; import com.cloudbees.jenkins.plugins.awscredentials.AmazonWebServicesCredentials; import hudson.Extension; import hudson.model.Computer; import hudson.model.Descriptor; import hudson.model.Label; import hudson.model.Node; import hudson.slaves.Cloud; import hudson.slaves.JNLPLauncher; import hudson.slaves.NodeProvisioner; import hudson.util.FormValidation; import hudson.util.ListBoxModel; import jenkins.model.Jenkins; import jenkins.model.JenkinsLocationConfiguration; /** * @author <a href="mailto:nicolas.deloof@gmail.com">Nicolas De Loof</a> */ public class ECSCloud extends Cloud { private static final Logger LOGGER = Logger.getLogger(ECSCloud.class.getName()); private static final int DEFAULT_SLAVE_TIMEOUT = 900; private final List<ECSTaskTemplate> templates; /** * Id of the {@link AmazonWebServicesCredentials} used to connect to Amazon ECS */ @Nonnull private final String credentialsId; private final String cluster; private String regionName; /** * Tunnel connection through */ @CheckForNull private String tunnel; private String jenkinsUrl; private int slaveTimoutInSeconds; private ECSService ecsService; @DataBoundConstructor public ECSCloud(String name, List<ECSTaskTemplate> templates, @Nonnull String credentialsId, String cluster, String regionName, String jenkinsUrl, int slaveTimoutInSeconds) throws InterruptedException{ super(name); this.credentialsId = credentialsId; this.cluster = cluster; this.templates = templates; this.regionName = regionName; LOGGER.log(Level.INFO, "Create cloud {0} on ECS cluster {1} on the region {2}", new Object[]{name, cluster, regionName}); if(StringUtils.isNotBlank(jenkinsUrl)) { this.jenkinsUrl = jenkinsUrl; } else { this.jenkinsUrl = JenkinsLocationConfiguration.get().getUrl(); } if(slaveTimoutInSeconds > 0) { this.slaveTimoutInSeconds = slaveTimoutInSeconds; } else { this.slaveTimoutInSeconds = DEFAULT_SLAVE_TIMEOUT; } } synchronized ECSService getEcsService() { if (ecsService == null) { ecsService = new ECSService(credentialsId, regionName); } return ecsService; } AmazonECSClient getAmazonECSClient() { return getEcsService().getAmazonECSClient(); } public List<ECSTaskTemplate> getTemplates() { return templates; } public String getCredentialsId() { return credentialsId; } public String getCluster() { return cluster; } public String getRegionName() { return regionName; } public void setRegionName(String regionName) { this.regionName = regionName; } public String getTunnel() { return tunnel; } @DataBoundSetter public void setTunnel(String tunnel) { this.tunnel = tunnel; } @CheckForNull private static AmazonWebServicesCredentials getCredentials(@Nullable String credentialsId) { return AWSCredentialsHelper.getCredentials(credentialsId, Jenkins.getActiveInstance()); } @Override public boolean canProvision(Label label) { return getTemplate(label) != null; } private ECSTaskTemplate getTemplate(Label label) { if (label == null) { return null; } for (ECSTaskTemplate t : templates) { if (label.matches(t.getLabelSet())) { return t; } } return null; } @Override public Collection<NodeProvisioner.PlannedNode> provision(Label label, int excessWorkload) { try { List<NodeProvisioner.PlannedNode> r = new ArrayList<NodeProvisioner.PlannedNode>(); final ECSTaskTemplate template = getTemplate(label); for (int i = 1; i <= excessWorkload; i++) { r.add(new NodeProvisioner.PlannedNode(template.getDisplayName(), Computer.threadPoolForRemoting .submit(new ProvisioningCallback(template, label)), 1)); } return r; } catch (Exception e) { LOGGER.log(Level.WARNING, "Failed to provision ECS slave", e); return Collections.emptyList(); } } void deleteTask(String taskArn, String clusterArn) { getEcsService().deleteTask(taskArn, clusterArn); } public int getSlaveTimoutInSeconds() { return slaveTimoutInSeconds; } public void setSlaveTimoutInSeconds(int slaveTimoutInSeconds) { this.slaveTimoutInSeconds = slaveTimoutInSeconds; } private class ProvisioningCallback implements Callable<Node> { private final ECSTaskTemplate template; @CheckForNull private Label label; public ProvisioningCallback(ECSTaskTemplate template, @Nullable Label label) { this.template = template; this.label = label; } public Node call() throws Exception { final ECSSlave slave; Date now = new Date(); Date timeout = new Date(now.getTime() + 1000 * slaveTimoutInSeconds); synchronized (cluster) { getEcsService().waitForSufficientClusterResources(timeout, template, cluster); String uniq = Long.toHexString(System.nanoTime()); slave = new ECSSlave(ECSCloud.this, name + "-" + uniq, template.getRemoteFSRoot(), template.getLabel(), new JNLPLauncher()); slave.setClusterArn(cluster); Jenkins.getInstance().addNode(slave); while (Jenkins.getInstance().getNode(slave.getNodeName()) == null) { Thread.sleep(1000); } LOGGER.log(Level.INFO, "Created Slave: {0}", slave.getNodeName()); try { String taskDefintionArn = getEcsService().registerTemplate(slave.getCloud(), template, cluster); String taskArn = getEcsService().runEcsTask(slave, template, cluster, getDockerRunCommand(slave), taskDefintionArn); LOGGER.log(Level.INFO, "Slave {0} - Slave Task Started : {1}", new Object[] { slave.getNodeName(), taskArn }); slave.setTaskArn(taskArn); } catch (Exception ex) { LOGGER.log(Level.WARNING, "Slave {0} - Cannot create ECS Task"); Jenkins.getInstance().removeNode(slave); throw ex; } } // now wait for slave to be online while (timeout.after(new Date())) { if (slave.getComputer() == null) { throw new IllegalStateException( "Slave " + slave.getNodeName() + " - Node was deleted, computer is null"); } if (slave.getComputer().isOnline()) { break; } LOGGER.log(Level.FINE, "Waiting for slave {0} (ecs task {1}) to connect since {2}.", new Object[] { slave.getNodeName(), slave.getTaskArn(), now }); Thread.sleep(1000); } if (!slave.getComputer().isOnline()) { final String msg = MessageFormat.format("ECS Slave {0} (ecs task {1}) not connected since {2} seconds", slave.getNodeName(), slave.getTaskArn(), now); LOGGER.log(Level.WARNING, msg); Jenkins.getInstance().removeNode(slave); throw new IllegalStateException(msg); } LOGGER.log(Level.INFO, "ECS Slave " + slave.getNodeName() + " (ecs task {0}) connected", slave.getTaskArn()); return slave; } } private Collection<String> getDockerRunCommand(ECSSlave slave) { Collection<String> command = new ArrayList<String>(); command.add("-url"); command.add(jenkinsUrl); if (StringUtils.isNotBlank(tunnel)) { command.add("-tunnel"); command.add(tunnel); } command.add(slave.getComputer().getJnlpMac()); command.add(slave.getComputer().getName()); return command; } @Extension public static class DescriptorImpl extends Descriptor<Cloud> { private static String CLOUD_NAME_PATTERN = "[a-z|A-Z|0-9|_|-]{1,127}"; @Override public String getDisplayName() { return Messages.DisplayName(); } public ListBoxModel doFillCredentialsIdItems() { return AWSCredentialsHelper.doFillCredentialsIdItems(Jenkins.getActiveInstance()); } public ListBoxModel doFillRegionNameItems() { final ListBoxModel options = new ListBoxModel(); for (Region region : RegionUtils.getRegions()) { options.add(region.getName()); } return options; } public ListBoxModel doFillClusterItems(@QueryParameter String credentialsId, @QueryParameter String regionName) { ECSService ecsService = new ECSService(credentialsId, regionName); try { final AmazonECSClient client = ecsService.getAmazonECSClient(); final ListBoxModel options = new ListBoxModel(); for (String arn : client.listClusters().getClusterArns()) { options.add(arn); } return options; } catch (AmazonClientException e) { // missing credentials will throw an "AmazonClientException: Unable to load AWS credentials from any provider in the chain" LOGGER.log(Level.INFO, "Exception searching clusters for credentials=" + credentialsId + ", regionName=" + regionName + ":" + e); LOGGER.log(Level.FINE, "Exception searching clusters for credentials=" + credentialsId + ", regionName=" + regionName, e); return new ListBoxModel(); } catch (RuntimeException e) { LOGGER.log(Level.INFO, "Exception searching clusters for credentials=" + credentialsId + ", regionName=" + regionName, e); return new ListBoxModel(); } } public FormValidation doCheckName(@QueryParameter String value) throws IOException, ServletException { if (value.length() > 0 && value.length() <= 127 && value.matches(CLOUD_NAME_PATTERN)) { return FormValidation.ok(); } return FormValidation.error("Up to 127 letters (uppercase and lowercase), numbers, hyphens, and underscores are allowed"); } } public static Region getRegion(String regionName) { if (StringUtils.isNotEmpty(regionName)) { return RegionUtils.getRegion(regionName); } else { return Region.getRegion(Regions.US_EAST_1); } } public String getJenkinsUrl() { return jenkinsUrl; } public void setJenkinsUrl(String jenkinsUrl) { this.jenkinsUrl = jenkinsUrl; } }
package com.jiahaoliuliu.nearestrestaurants; import com.actionbarsherlock.app.ActionBar; import com.actionbarsherlock.app.SherlockFragmentActivity; import com.actionbarsherlock.view.Menu; import com.actionbarsherlock.view.MenuItem; import com.actionbarsherlock.view.Window; import com.google.android.gms.maps.model.LatLng; import com.jiahaoliuliu.nearestrestaurants.interfaces.Callback; import com.jiahaoliuliu.nearestrestaurants.interfaces.OnPositionRequestedListener; import com.jiahaoliuliu.nearestrestaurants.interfaces.OnProgressBarShowRequestListener; import com.jiahaoliuliu.nearestrestaurants.interfaces.OnUpdatePositionListener; import com.jiahaoliuliu.nearestrestaurants.session.Session; import com.jiahaoliuliu.nearestrestaurants.utils.PositionTracker; import android.app.AlertDialog; import android.content.BroadcastReceiver; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.IntentFilter; import android.os.Bundle; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentTransaction; import android.util.Log; import android.view.KeyEvent; import android.widget.Toast; /** * The main class for which includes the map fragment and the list fragment. * It is the main fragment which creates the consistency between the fragments. * It is also the one which have the position of the user updated. * @author Jiahao Liu * */ public class NearestRestaurants extends SherlockFragmentActivity implements OnPositionRequestedListener, OnProgressBarShowRequestListener { private static final String LOG_TAG = NearestRestaurants.class.getSimpleName(); // System data private Context context; private ActionBar actionBar; private Menu actionBarMenu; private FragmentManager fragmentManager; // Callback used to deal with the asynchronous operations private Callback actionBarMenuCallback; // The customized id of the action bar button private MenuItem menuViewListItem; private MenuItem menuViewMapItem; // The customized menu buttons id. This is because the normal id, which starts // with 0, could cause confusion. private static final int MENU_VIEW_LIST_BUTTON_ID = 10000; private static final int MENU_VIEW_MAP_BUTTON_ID = 10001; // Session private Session session; // For the users positions private PositionTracker positionTracker; // The broadcast receiver for the position private MyPositionBroadcastReceiver myPositionBReceiver; private LatLng myPosition; // The fragments private NearestRestaurantsMapFragment mapFragment; private NearestRestaurantsListFragment listFragment; // The interface for the fragment private OnUpdatePositionListener onUpdatePositionListener; // The dialog used to warning the user that she is going to exit private AlertDialog exitAlertDialog; @Override protected void onCreate(Bundle savedInstanceState) { requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS); super.onCreate(savedInstanceState); setContentView(R.layout.nearest_restaurants_layout); context = this; actionBar = getSupportActionBar(); session = Session.getCurrentSession(context); fragmentManager = getSupportFragmentManager(); // Get the user's position positionTracker = new PositionTracker(context); // Register the broadcast receiver IntentFilter filter = new IntentFilter(PositionTracker.BROADCAST_POSITION_ACTION); myPositionBReceiver = new MyPositionBroadcastReceiver(); context.registerReceiver(myPositionBReceiver, filter); // The first fragment shown in the map fragment showMapFragment(); } @Override protected void onResume() { super.onResume(); // Show the users last position if it was set setSupportProgressBarIndeterminateVisibility(true); LatLng userLastPosition = session.getLastUserPosition(); if (userLastPosition != null) { myPosition = userLastPosition; Toast.makeText(context, getResources().getString(R.string.updating_users_position), Toast.LENGTH_LONG).show(); // Update the fragments position if (onUpdatePositionListener != null) { onUpdatePositionListener.updatePosition(myPosition); } } else { Toast.makeText(context, getResources().getString(R.string.looking_users_position), Toast.LENGTH_LONG).show(); } } @Override protected void onPause() { super.onPause(); // Disable any indeterminate progress bar setSupportProgressBarIndeterminateVisibility(false); } /** * The Broadcast receiver registered to receive the position update * Intent from the position tracker. */ private class MyPositionBroadcastReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { Log.v(LOG_TAG, "New position received."); double latitude = intent.getDoubleExtra(PositionTracker.BROADCAST_POSITION_LATITUDE, PositionTracker.DEFAULT_LATITUDE); double longitude = intent.getDoubleExtra(PositionTracker.BROADCAST_POSITION_LONGITUDE, PositionTracker.DEFAULT_LONGITUDE); if (latitude == PositionTracker.DEFAULT_LATITUDE || longitude == PositionTracker.DEFAULT_LONGITUDE) { Log.e(LOG_TAG, "Wrong position found: " + latitude + ":" + longitude); return; } Log.v(LOG_TAG, "The new position is " + latitude + " ," + longitude); // Update the position myPosition = new LatLng(latitude, longitude); session.setLastUserPosition(myPosition); if (onUpdatePositionListener != null) { onUpdatePositionListener.updatePosition(myPosition); } // Disable the progress bar setSupportProgressBarIndeterminateVisibility(false); } } @Override protected void onDestroy() { super.onDestroy(); positionTracker.finish(); // Unregister the Broadcast receiver if (myPositionBReceiver != null) { context.unregisterReceiver(myPositionBReceiver); } } // Use the action bar to switch views @Override public boolean onCreateOptionsMenu(Menu menu) { // Get the value of Menu actionBarMenu = menu; if (actionBarMenuCallback != null) { actionBarMenuCallback.done(); } return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Show the list fragment if (item.getItemId() == MENU_VIEW_LIST_BUTTON_ID) { showListFragment(); // Show the map fragment } else if (item.getItemId() == MENU_VIEW_MAP_BUTTON_ID) { showMapFragment(); } return true; } /** * Show the map fragment */ private void showMapFragment() { // Create it if it has not been created before if (mapFragment == null) { mapFragment = new NearestRestaurantsMapFragment(); } FragmentTransaction ft = fragmentManager.beginTransaction(); ft.replace(R.id.content_frame, mapFragment, NearestRestaurantsMapFragment.class.toString()); ft.commit(); // Update the onUpdatePositionListener try { onUpdatePositionListener = (OnUpdatePositionListener)mapFragment; } catch (ClassCastException classCastException) { Log.e(LOG_TAG, "The fragment must implements the OnUpdatePositionListener", classCastException); } // Modify the action bar menu to adapt it to the map fragment if (actionBarMenu == null) { actionBarMenuCallback = new Callback() { @Override public void done() { showMapActionBar(); // Null the call back so it won't be // called again actionBarMenuCallback = null; } }; } else { showMapActionBar(); } } /** * Show the action bar related with the map fragment. */ private void showMapActionBar() { if (actionBarMenu == null) { Log.e(LOG_TAG, "Trying to adapt the action bar to the map when it is null"); return; } // Remove any previous menu item actionBarMenu.clear(); // Set the initial state of the menu item menuViewListItem = actionBarMenu.add(Menu.NONE, MENU_VIEW_LIST_BUTTON_ID, Menu .NONE, getResources().getString(R.string.action_bar_show_list)); menuViewListItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS | MenuItem.SHOW_AS_ACTION_WITH_TEXT); } /** * Show the list fragment */ private void showListFragment() { if (listFragment == null) { listFragment = new NearestRestaurantsListFragment(); } FragmentTransaction ft = fragmentManager.beginTransaction(); ft.replace(R.id.content_frame, listFragment, NearestRestaurantsListFragment.class.toString()); ft.commit(); // Update the onUpdatePositionListener try { onUpdatePositionListener = (OnUpdatePositionListener)listFragment; } catch (ClassCastException classCastException) { Log.e(LOG_TAG, "The fragment must implements the OnUpdatePositionListener", classCastException); } // Modify the action bar menu to adapt it to the map fragment if (actionBarMenu == null) { actionBarMenuCallback = new Callback() { @Override public void done() { showListActionBar(); // Null the call back so it won't be // called again actionBarMenuCallback = null; } }; } else { showListActionBar(); } } /** * Show the action bar related with the map fragment */ private void showListActionBar() { if (actionBarMenu == null) { Log.e(LOG_TAG, "Trying to adapt the action bar to the map when it is null"); return; } // Remove any previous menu item actionBarMenu.clear(); // Set the initial state of the menu item menuViewMapItem = actionBarMenu.add(Menu.NONE, MENU_VIEW_MAP_BUTTON_ID, Menu .NONE, getResources().getString(R.string.action_bar_show_map)); menuViewMapItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS | MenuItem.SHOW_AS_ACTION_WITH_TEXT); } @Override public LatLng requestPosition() { return myPosition; } @Override public void showProgressBar() { setSupportProgressBarIndeterminateVisibility(true); } @Override public void hidePorgressBar() { setSupportProgressBarIndeterminateVisibility(false); } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_BACK) { if (exitAlertDialog == null) { exitAlertDialog = createExitAlertDialog(); } exitAlertDialog.show(); return true; // To finish here and say the key has been handled } return super.onKeyDown(keyCode, event); } private AlertDialog createExitAlertDialog() { return new AlertDialog.Builder( context) .setTitle(getResources().getString(R.string.alert_exit_title)) .setMessage(getResources().getString(R.string.alert_exit_message)) .setPositiveButton(getResources().getString(R.string.alert_exit_positive_button), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { finish(); } }) .setNegativeButton(getResources().getString(R.string.alert_exit_negative_button), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }) .create(); } }
package nu.validator.client; import java.io.File; import java.io.InputStream; import java.io.IOException; import java.io.OutputStream; import java.net.URL; import java.util.ArrayList; import java.util.List; import nu.validator.htmlparser.sax.XmlSerializer; import nu.validator.messages.GnuMessageEmitter; import nu.validator.messages.JsonMessageEmitter; import nu.validator.messages.MessageEmitterAdapter; import nu.validator.messages.TextMessageEmitter; import nu.validator.messages.XmlMessageEmitter; import nu.validator.servlet.imagereview.ImageCollector; import nu.validator.source.SourceCode; import nu.validator.validation.SimpleDocumentValidator; import nu.validator.validation.SimpleDocumentValidator.SchemaReadException; import nu.validator.xml.SystemErrErrorHandler; import org.xml.sax.InputSource; import org.xml.sax.SAXException; import org.xml.sax.SAXParseException; /** * * Simple command-line validator for HTML/XHTML files. */ public class SimpleCommandLineValidator { private static SimpleDocumentValidator validator; private static OutputStream out; private static MessageEmitterAdapter errorHandler; private static boolean verbose; private static boolean errorsOnly; private static boolean loadEntities; private static boolean noStream; private static boolean forceHTML; private static boolean asciiQuotes; private static int lineOffset; private static enum OutputFormat { HTML, XHTML, TEXT, XML, JSON, RELAXED, SOAP, UNICORN, GNU } private static OutputFormat outputFormat; public static void main(String[] args) throws SAXException, Exception { out = System.err; System.setProperty("org.whattf.datatype.warn", "true"); errorsOnly = false; forceHTML = false; loadEntities = false; noStream = false; lineOffset = 0; asciiQuotes = false; verbose = false; String version = "dev"; String outFormat = null; String schemaUrl = null; boolean hasFileArgs = false; boolean readFromStdIn = false; int fileArgsStart = 0; if (args.length == 0) { usage(); System.exit(1); } for (int i = 0; i < args.length; i++) { if (args[i].equals("-")) { readFromStdIn = true; break; } else if (!args[i].startsWith(" hasFileArgs = true; fileArgsStart = i; break; } else { if ("--verbose".equals(args[i])) { verbose = true; } else if ("--errors-only".equals(args[i])) { errorsOnly = true; System.setProperty("org.whattf.datatype.warn", "false"); } else if ("--format".equals(args[i])) { outFormat = args[++i]; } else if ("--version".equals(args[i])) { System.out.println(version); System.exit(0); } else if ("--help".equals(args[i])) { help(); System.exit(0); } else if ("--html".equals(args[i])) { forceHTML = true; } else if ("--entities".equals(args[i])) { loadEntities = true; } else if ("--no-stream".equals(args[i])) { noStream = true; } else if ("--schema".equals(args[i])) { schemaUrl = args[++i]; if (!schemaUrl.startsWith("http:")) { System.err.println("error: The \"--schema\" option" + " requires a URL for a schema."); System.exit(1); } } } } if (schemaUrl == null) { schemaUrl = "http://s.validator.nu/html5-rdfalite.rnc"; } if (outFormat == null) { outputFormat = OutputFormat.GNU; } else { if ("text".equals(outFormat)) { outputFormat = OutputFormat.TEXT; } else if ("gnu".equals(outFormat)) { outputFormat = OutputFormat.GNU; } else if ("xml".equals(outFormat)) { outputFormat = OutputFormat.XML; } else if ("json".equals(outFormat)) { outputFormat = OutputFormat.JSON; } else { System.err.printf("Error: Unsupported output format \"%s\"." + " Must be \"gnu\", \"xml\", \"json\"," + " or \"text\".\n", outFormat); System.exit(1); } } if (readFromStdIn) { InputSource is = new InputSource(System.in); validator = new SimpleDocumentValidator(); setup(schemaUrl); validator.checkHtmlInputSource(is); end(); } else if (hasFileArgs) { List<File> files = new ArrayList<File>(); for (int i = fileArgsStart; i < args.length; i++) { files.add(new File(args[i])); } validator = new SimpleDocumentValidator(); setup(schemaUrl); checkFiles(files); end(); } else { System.err.printf("\nError: No documents specified.\n"); usage(); System.exit(1); } } private static void setup(String schemaUrl) throws SAXException, Exception { setErrorHandler(); errorHandler.setHtml(true); try { validator.setUpMainSchema(schemaUrl, new SystemErrErrorHandler()); } catch (SchemaReadException e) { System.out.println(e.getMessage() + " Terminating."); System.exit(1); } catch (StackOverflowError e) { System.out.println("StackOverflowError" + " while evaluating HTML schema."); System.out.println("The checker requires a java thread stack size" + " of at least 512k."); System.out.println("Consider invoking java with the -Xss" + " option. For example:"); System.out.println("\n java -Xss512k -jar ~/vnu.jar FILE.html"); System.exit(1); } validator.setUpValidatorAndParsers(errorHandler, noStream, loadEntities); } private static void end() throws SAXException { errorHandler.end("Document checking completed. No errors found.", "Document checking completed."); if (errorHandler.getErrors() > 0 || errorHandler.getFatalErrors() > 0) { System.exit(1); } } private static void checkFiles(List<File> files) throws SAXException, IOException { for (File file : files) { if (file.isDirectory()) { recurseDirectory(file); } else { checkHtmlFile(file); } } } private static void recurseDirectory(File directory) throws SAXException, IOException { File[] files = directory.listFiles(); for (int i = 0; i < files.length; i++) { File file = files[i]; if (file.isDirectory()) { recurseDirectory(file); } else { checkHtmlFile(file); } } } private static void checkHtmlFile(File file) throws IOException { try { String path = file.getPath(); if (path.matches("^http:/[^/].+$")) { path = "http://" + path.substring(path.indexOf("/") + 1); emitFilename(path); try { validator.checkHttpURL(new URL(path)); } catch (IOException e) { errorHandler.error(new SAXParseException(e.toString(), null, path, -1, -1)); } } else if (path.matches("^https:/[^/].+$")) { path = "https://" + path.substring(path.indexOf("/") + 1); emitFilename(path); try { validator.checkHttpURL(new URL(path)); } catch (IOException e) { errorHandler.error(new SAXParseException(e.toString(), null, path, -1, -1)); } } else if (!file.exists()) { if (verbose) { errorHandler.warning(new SAXParseException( "File not found.", null, file.toURI().toURL().toString(), -1, -1)); } return; } else if (isHtml(file)) { emitFilename(path); validator.checkHtmlFile(file, true); } else if (isXhtml(file)) { emitFilename(path); if (forceHTML) { validator.checkHtmlFile(file, true); } else { validator.checkXmlFile(file); } } else { if (verbose) { errorHandler.warning(new SAXParseException( "File was not checked. Files must have .html," + " .xhtml, .htm, or .xht extensions.", null, file.toURI().toURL().toString(), -1, -1)); } } } catch (SAXException e) { if (!errorsOnly) { System.err.printf("\"%s\":-1:-1: warning: %s\n", file.toURI().toURL().toString(), e.getMessage()); } } } private static boolean isXhtml(File file) { String name = file.getName(); return (name.endsWith(".xhtml") || name.endsWith(".xht")); } private static boolean isHtml(File file) { String name = file.getName(); return (name.endsWith(".html") || name.endsWith(".htm")); } private static void emitFilename(String name) { if (verbose) { System.out.println(name); } } private static void setErrorHandler() { SourceCode sourceCode = new SourceCode(); ImageCollector imageCollector = new ImageCollector(sourceCode); boolean showSource = false; if (outputFormat == OutputFormat.TEXT) { errorHandler = new MessageEmitterAdapter(sourceCode, showSource, imageCollector, lineOffset, true, new TextMessageEmitter( out, asciiQuotes)); } else if (outputFormat == OutputFormat.GNU) { errorHandler = new MessageEmitterAdapter(sourceCode, showSource, imageCollector, lineOffset, true, new GnuMessageEmitter( out, asciiQuotes)); } else if (outputFormat == OutputFormat.XML) { errorHandler = new MessageEmitterAdapter(sourceCode, showSource, imageCollector, lineOffset, true, new XmlMessageEmitter( new XmlSerializer(out))); } else if (outputFormat == OutputFormat.JSON) { String callback = null; errorHandler = new MessageEmitterAdapter(sourceCode, showSource, imageCollector, lineOffset, true, new JsonMessageEmitter( new nu.validator.json.Serializer(out), callback)); } else { throw new RuntimeException("Bug. Should be unreachable."); } errorHandler.setErrorsOnly(errorsOnly); } private static void usage() { System.out.println("Usage:"); System.out.println(""); System.out.println(" java -jar vnu.jar [--errors-only] [--no-stream]"); System.out.println(" [--format gnu|xml|json|text] [--help] [--html]"); System.out.println(" [--verbose] [--version] FILES"); System.out.println(""); System.out.println(" java -cp vnu.jar nu.validator.servlet.Main 8888"); System.out.println(""); System.out.println(" java -cp vnu.jar nu.validator.client.HttpClient FILES"); System.out.println(""); System.out.println("For detailed usage information, use \"java -jar vnu.jar --help\" or see:"); System.out.println(""); System.out.println(" http://validator.github.io/"); System.out.println(""); System.out.println("To read from stdin, use \"-\" as the filename, like this: \"java -jar vnu.jar - \"."); } private static void help() { InputStream help = SimpleCommandLineValidator.class.getClassLoader().getResourceAsStream( "nu/validator/localentities/files/cli-help"); try { System.out.println(""); for (int b = help.read(); b != -1; b = help.read()) { System.out.write(b); } help.close(); } catch (IOException e) { throw new RuntimeException(e); } } }
package com.dumptruckman.chestrestock.command; import com.dumptruckman.chestrestock.ChestRestockPlugin; import com.dumptruckman.chestrestock.api.CRChest; import com.dumptruckman.chestrestock.api.CRChestOptions; import com.dumptruckman.chestrestock.util.Language; import com.dumptruckman.chestrestock.util.Perms; import com.dumptruckman.minecraft.pluginbase.config.ConfigEntry; import org.bukkit.block.Block; import org.bukkit.entity.Player; import org.bukkit.inventory.InventoryHolder; import java.lang.reflect.Field; import java.util.HashMap; import java.util.List; import java.util.Map; public class SetCommand extends TargetedChestRestockCommand { private static final Map<String, ConfigEntry> PROPS_MAP = new HashMap<String, ConfigEntry>(); private static String propsString = ""; static { for (Field field : CRChestOptions.class.getFields()) { if (!ConfigEntry.class.isAssignableFrom(field.getType())) { continue; } try { ConfigEntry entry = (ConfigEntry) field.get(null); PROPS_MAP.put(entry.getName(), entry); } catch (IllegalAccessException ignore) { } } for (String key : PROPS_MAP.keySet()) { if (!propsString.isEmpty()) { propsString += ", "; } propsString += key; } } public SetCommand(ChestRestockPlugin plugin) { super(plugin); this.setName(messager.getMessage(Language.CMD_SET_NAME)); this.setCommandUsage("/" + plugin.getCommandPrefixes().get(0) + " set [property [value]]"); this.addPrefixedKey(" set"); this.setArgRange(0, 500); this.addCommandExample("/" + plugin.getCommandPrefixes().get(0) + " set"); this.addCommandExample("/" + plugin.getCommandPrefixes().get(0) + " set unique"); this.addCommandExample("/" + plugin.getCommandPrefixes().get(0) + " set period 300"); this.addCommandExample("/" + plugin.getCommandPrefixes().get(0) + " set restockmode fixed"); this.setPermission(Perms.CMD_SET.getPermission()); } @Override public void runCommand(Player player, Block block, List<String> args) { CRChest rChest = chestManager.getChest(block, (InventoryHolder) block.getState()); if (args.size() == 0) { if (rChest == null) { messager.normal(Language.CMD_SET_NEW_CMD, player); } else { messager.normal(Language.CMD_SET_LIST_PROPS, player, propsString); } } else if (args.size() == 1) { ConfigEntry configEntry = PROPS_MAP.get(args.get(0).toLowerCase()); if (configEntry == null) { messager.bad(Language.CMD_SET_INVALID_PROP, player, args.get(0)); return; } if (configEntry.getDescription() != null) { messager.normal(configEntry.getDescription(), player); } if (configEntry.getType().equals(Boolean.class)) { messager.normal(Language.CMD_SET_POSSIBLE_VALUES, player, configEntry.getName(), "true/false"); } else if (configEntry.getType().equals(Integer.class)) { messager.normal(Language.CMD_SET_POSSIBLE_VALUES, player, configEntry.getName(), "a number"); } else if (configEntry.getType().equals(String.class)) { messager.normal(Language.CMD_SET_POSSIBLE_VALUES, player, configEntry.getName(), "a word"); } } else if (args.size() > 1) { ConfigEntry configEntry = PROPS_MAP.get(args.get(0).toLowerCase()); if (configEntry == null) { messager.bad(Language.CMD_SET_INVALID_PROP, player, args.get(0)); return; } if (rChest == null) { messager.normal(Language.CMD_NOT_RCHEST, player); return; } String value; if (args.size() == 2) { value = args.get(1).toLowerCase(); } else { StringBuilder builder = new StringBuilder(); for (int i = 1; i < args.size(); i++) { if (!builder.toString().isEmpty()) { builder.append(" "); } builder.append(args.get(i)); } value = builder.toString(); } if (configEntry == CRChest.GLOBAL_MESSAGE && value.equalsIgnoreCase("clear")) { value = ""; } if (!configEntry.isValid(value)) { messager.bad(Language.CMD_SET_INVALID_VALUE, player, plugin.getCommandPrefixes().get(0) + " set " + args.get(0)); return; } try { rChest.set(configEntry, configEntry.deserialize(value)); rChest.save(); chestManager.pollingCheckIn(rChest); } catch (NumberFormatException e) { messager.bad(Language.CMD_SET_INVALID_VALUE, player, plugin.getCommandPrefixes().get(0) + " set " + args.get(0)); return; } messager.good(Language.CMD_SET_SUCCESS, player, configEntry.getName(), rChest.get(configEntry)); } } }
package com.faforever.client.chat; import com.faforever.client.chat.avatar.AvatarService; import com.faforever.client.fx.JavaFxUtil; import com.faforever.client.game.GameInfoBean; import com.faforever.client.game.GameService; import com.faforever.client.game.GameStatus; import com.faforever.client.game.GamesController; import com.faforever.client.game.JoinGameHelper; import com.faforever.client.game.PlayerCardTooltipController; import com.faforever.client.i18n.I18n; import com.faforever.client.notification.ImmediateNotification; import com.faforever.client.notification.NotificationService; import com.faforever.client.notification.ReportAction; import com.faforever.client.notification.Severity; import com.faforever.client.preferences.ChatPrefs; import com.faforever.client.preferences.PreferencesService; import com.faforever.client.replay.ReplayService; import com.faforever.client.reporting.ReportingService; import com.faforever.client.theme.ThemeService; import com.google.common.eventbus.EventBus; import javafx.application.Platform; import javafx.beans.binding.Bindings; import javafx.beans.value.ChangeListener; import javafx.beans.value.WeakChangeListener; import javafx.collections.MapChangeListener; import javafx.collections.WeakMapChangeListener; import javafx.fxml.FXML; import javafx.scene.control.Label; import javafx.scene.control.Tooltip; import javafx.scene.image.Image; import javafx.scene.image.ImageView; import javafx.scene.input.ContextMenuEvent; import javafx.scene.input.MouseButton; import javafx.scene.input.MouseEvent; import javafx.scene.layout.Pane; import javafx.scene.paint.Color; import javafx.stage.PopupWindow; import org.springframework.context.ApplicationContext; import org.springframework.util.StringUtils; import javax.annotation.PostConstruct; import javax.annotation.Resource; import java.io.IOException; import static com.faforever.client.chat.ChatColorMode.CUSTOM; import static com.faforever.client.chat.SocialStatus.SELF; import static com.faforever.client.util.RatingUtil.getGlobalRating; import static com.faforever.client.util.RatingUtil.getLeaderboardRating; import static java.util.Collections.singletonList; import static java.util.Locale.US; public class ChatUserItemController { private static final String CLAN_TAG_FORMAT = "[%s]"; @FXML Pane chatUserItemRoot; @FXML ImageView countryImageView; @FXML ImageView avatarImageView; @FXML Label usernameLabel; @FXML Label clanLabel; @FXML ImageView statusImageView; @Resource ApplicationContext applicationContext; @Resource AvatarService avatarService; @Resource CountryFlagService countryFlagService; @Resource GameService gameService; @Resource PreferencesService preferencesService; @Resource ChatService chatService; @Resource GamesController gamesController; @Resource ReplayService replayService; @Resource I18n i18n; @Resource ThemeService themeService; @Resource NotificationService notificationService; @Resource ReportingService reportingService; @Resource JoinGameHelper joinGameHelper; @Resource EventBus eventBus; private PlayerInfoBean playerInfoBean; private boolean colorsAllowedInPane; private ChangeListener<ChatColorMode> colorModeChangeListener; private MapChangeListener<? super String, ? super Color> colorPerUserMapChangeListener; private ChangeListener<String> avatarChangeListener; private ChangeListener<String> clanChangeListener; private ChangeListener<GameStatus> gameStatusChangeListener; private PlayerCardTooltipController playerCardTooltipController; @FXML void initialize() { chatUserItemRoot.setUserData(this); } @FXML void onContextMenuRequested(ContextMenuEvent event) { ChatUserContextMenuController contextMenuController = applicationContext.getBean(ChatUserContextMenuController.class); contextMenuController.setPlayerInfoBean(playerInfoBean); contextMenuController.getContextMenu().show(chatUserItemRoot.getScene().getWindow(), event.getScreenX(), event.getScreenY()); } @FXML void onUsernameClicked(MouseEvent mouseEvent) { if (mouseEvent.getButton() == MouseButton.PRIMARY && mouseEvent.getClickCount() == 2) { eventBus.post(new InitiatePrivateChatEvent(playerInfoBean.getUsername())); } } @PostConstruct void postConstruct() { ChatPrefs chatPrefs = preferencesService.getPreferences().getChat(); colorModeChangeListener = (observable, oldValue, newValue) -> configureColor(); colorPerUserMapChangeListener = change -> { String lowerUsername = playerInfoBean.getUsername().toLowerCase(US); if (lowerUsername.equalsIgnoreCase(change.getKey())) { Color newColor = chatPrefs.getUserToColor().get(lowerUsername); assignColor(newColor); } }; avatarChangeListener = (observable, oldValue, newValue) -> Platform.runLater(() -> setAvatarUrl(newValue)); clanChangeListener = (observable, oldValue, newValue) -> Platform.runLater(() -> setClanTag(newValue)); gameStatusChangeListener = (observable, oldValue, newValue) -> Platform.runLater(() -> setGameStatus(newValue)); joinGameHelper.setParentNode(getRoot()); } private void configureColor() { ChatPrefs chatPrefs = preferencesService.getPreferences().getChat(); if (playerInfoBean.getSocialStatus() == SELF) { usernameLabel.getStyleClass().add(SELF.getCssClass()); clanLabel.getStyleClass().add(SELF.getCssClass()); return; } Color color = null; String lowerUsername = playerInfoBean.getUsername().toLowerCase(US); ChatUser chatUser = chatService.getOrCreateChatUser(lowerUsername); if (chatPrefs.getChatColorMode() == CUSTOM) { synchronized (chatPrefs.getUserToColor()) { if (chatPrefs.getUserToColor().containsKey(lowerUsername)) { color = chatPrefs.getUserToColor().get(lowerUsername); } chatPrefs.getUserToColor().addListener(new WeakMapChangeListener<>(colorPerUserMapChangeListener)); } } else if (chatPrefs.getChatColorMode() == ChatColorMode.RANDOM && colorsAllowedInPane) { color = ColorGeneratorUtil.generateRandomColor(chatUser.getUsername().hashCode()); } chatUser.setColor(color); assignColor(color); } private void assignColor(Color color) { if (color != null) { usernameLabel.setStyle(String.format("-fx-text-fill: %s", JavaFxUtil.toRgbCode(color))); clanLabel.setStyle(String.format("-fx-text-fill: %s", JavaFxUtil.toRgbCode(color))); } else { usernameLabel.setStyle(""); clanLabel.setStyle(""); } } private void setAvatarUrl(String avatarUrl) { if (StringUtils.isEmpty(avatarUrl)) { avatarImageView.setVisible(false); } else { avatarImageView.setImage(avatarService.loadAvatar(avatarUrl)); avatarImageView.setVisible(true); } } private void setClanTag(String newValue) { if (StringUtils.isEmpty(newValue)) { clanLabel.setVisible(false); } else { clanLabel.setText(String.format(CLAN_TAG_FORMAT, newValue)); clanLabel.setVisible(true); } } public void setGameStatus(GameStatus gameStatus) { Image statusImage; switch (gameStatus) { case PLAYING: statusImage = themeService.getThemeImage(ThemeService.PLAYING_STATUS_IMAGE); break; case HOST: statusImage = themeService.getThemeImage(ThemeService.HOSTING_STATUS_IMAGE); break; case LOBBY: statusImage = themeService.getThemeImage(ThemeService.LOBBY_STATUS_IMAGE); break; default: statusImage = null; } statusImageView.setImage(statusImage); statusImageView.setVisible(statusImageView.getImage() != null); } public Pane getRoot() { return chatUserItemRoot; } public PlayerInfoBean getPlayerInfoBean() { return playerInfoBean; } public void setPlayerInfoBean(PlayerInfoBean playerInfoBean) { this.playerInfoBean = playerInfoBean; configureColor(); addChatColorModeListener(); configureCountryImageView(); configureAvatarImageView(); configureClanLabel(); configureGameStatusView(); configureTooltip(); usernameLabel.setText(playerInfoBean.getUsername()); } private void addChatColorModeListener() { ChatPrefs chatPrefs = preferencesService.getPreferences().getChat(); chatPrefs.chatColorModeProperty().addListener(new WeakChangeListener<>(colorModeChangeListener)); } private void configureCountryImageView() { setCountry(playerInfoBean.getCountry()); Tooltip countryTooltip = new Tooltip(playerInfoBean.getCountry()); countryTooltip.textProperty().bind(playerInfoBean.countryProperty()); Tooltip.install(countryImageView, countryTooltip); } private void configureAvatarImageView() { playerInfoBean.avatarUrlProperty().addListener(new WeakChangeListener<>(avatarChangeListener)); setAvatarUrl(playerInfoBean.getAvatarUrl()); Tooltip avatarTooltip = new Tooltip(playerInfoBean.getAvatarTooltip()); avatarTooltip.textProperty().bind(playerInfoBean.avatarTooltipProperty()); avatarTooltip.setAnchorLocation(PopupWindow.AnchorLocation.CONTENT_TOP_LEFT); Tooltip.install(avatarImageView, avatarTooltip); } private void configureClanLabel() { setClanTag(playerInfoBean.getClan()); playerInfoBean.clanProperty().addListener(new WeakChangeListener<>(clanChangeListener)); } private void configureGameStatusView() { setGameStatus(playerInfoBean.getGameStatus()); playerInfoBean.gameStatusProperty().addListener(new WeakChangeListener<>(gameStatusChangeListener)); } private void configureTooltip() { if (playerInfoBean.getChatOnly()) { return; } // FIXME #294 Tooltip tooltip = new Tooltip(); Tooltip.install(clanLabel, tooltip); Tooltip.install(usernameLabel, tooltip); Bindings.createStringBinding( () -> i18n.get("userInfo.ratingFormat", getGlobalRating(playerInfoBean), getLeaderboardRating(playerInfoBean)), playerInfoBean.leaderboardRatingMeanProperty(), playerInfoBean.leaderboardRatingDeviationProperty(), playerInfoBean.globalRatingMeanProperty(), playerInfoBean.globalRatingDeviationProperty() ); } private void setCountry(String country) { if (StringUtils.isEmpty(country)) { countryImageView.setVisible(false); } else { countryImageView.setImage(countryFlagService.loadCountryFlag(country)); countryImageView.setVisible(true); } } @FXML void onMouseEnterGameStatus() { if (playerInfoBean.getGameStatus() == GameStatus.NONE) { return; } GameStatusTooltipController gameStatusTooltipController = applicationContext.getBean(GameStatusTooltipController.class); gameStatusTooltipController.setGameInfoBean(gameService.getByUid(playerInfoBean.getGameUid())); Tooltip statusTooltip = new Tooltip(); statusTooltip.setGraphic(gameStatusTooltipController.getRoot()); Tooltip.install(statusImageView, statusTooltip); } @FXML void onMouseEnterUsername() { if (playerInfoBean.getChatOnly()) { return; } if (playerCardTooltipController != null) { return; } playerCardTooltipController = applicationContext.getBean(PlayerCardTooltipController.class); playerCardTooltipController.setPlayer(playerInfoBean); Tooltip statusTooltip = new Tooltip(); statusTooltip.setGraphic(playerCardTooltipController.getRoot()); Tooltip.install(usernameLabel, statusTooltip); } @FXML void onMouseClickGameStatus(MouseEvent mouseEvent) { GameStatus gameStatus = playerInfoBean.getGameStatus(); if (gameStatus == GameStatus.NONE) { return; } if (mouseEvent.getButton() == MouseButton.PRIMARY && mouseEvent.getClickCount() == 2) { int uid = playerInfoBean.getGameUid(); if (gameStatus == GameStatus.LOBBY || gameStatus == GameStatus.HOST) { GameInfoBean gameInfoBean = gameService.getByUid(uid); joinGameHelper.join(gameInfoBean); } else if (gameStatus == GameStatus.PLAYING) { try { replayService.runLiveReplay(uid, playerInfoBean.getId()); } catch (IOException e) { notificationService.addNotification(new ImmediateNotification( i18n.get("errorTitle"), i18n.get("replayCouldNotBeStarted"), Severity.ERROR, e, singletonList(new ReportAction(i18n, reportingService, e)) )); } } } } public void setColorsAllowedInPane(boolean colorsAllowedInPane) { this.colorsAllowedInPane = colorsAllowedInPane; configureColor(); } public void setVisible(boolean visible) { chatUserItemRoot.setVisible(visible); chatUserItemRoot.setManaged(visible); } }
package com.redhat.ceylon.compiler.typechecker.context; import com.redhat.ceylon.compiler.typechecker.io.ArtifactProvider; import com.redhat.ceylon.compiler.typechecker.io.VFS; import com.redhat.ceylon.compiler.typechecker.model.Modules; /** * Keep compiler contextual information like the package stack and the current module * * @author Emmanuel Bernard <emmanuel@hibernate.org> */ public class Context { private ArtifactProvider artifactProvider; private Modules modules; private VFS vfs; public Context(VFS vfs) { this.vfs = vfs; this.artifactProvider = new ArtifactProvider(vfs); } public Modules getModules() { return modules; } public void setModules(Modules modules) { this.modules = modules; } public ArtifactProvider getArtifactProvider() { return artifactProvider; } public VFS getVfs() { return vfs; } }
package com.foundationdb.sql.optimizer.rule; import com.foundationdb.ais.model.Column; import com.foundationdb.ais.model.ColumnContainer; import com.foundationdb.ais.model.Routine; import com.foundationdb.qp.operator.QueryContext; import com.foundationdb.server.error.AkibanInternalException; import com.foundationdb.server.error.SQLParserInternalException; import com.foundationdb.server.types.service.OverloadResolver; import com.foundationdb.server.types.service.OverloadResolver.OverloadResult; import com.foundationdb.server.types.service.TypesRegistryService; import com.foundationdb.server.types.service.TCastResolver; import com.foundationdb.server.types.ErrorHandlingMode; import com.foundationdb.server.types.LazyList; import com.foundationdb.server.types.LazyListBase; import com.foundationdb.server.types.TCast; import com.foundationdb.server.types.TClass; import com.foundationdb.server.types.TExecutionContext; import com.foundationdb.server.types.TInstance; import com.foundationdb.server.types.TKeyComparable; import com.foundationdb.server.types.TOverloadResult; import com.foundationdb.server.types.TPreptimeContext; import com.foundationdb.server.types.TPreptimeValue; import com.foundationdb.server.types.aksql.aktypes.AkBool; import com.foundationdb.server.types.common.types.StringAttribute; import com.foundationdb.server.types.common.types.TBinary; import com.foundationdb.server.types.common.types.TString; import com.foundationdb.server.types.common.types.TypesTranslator; import com.foundationdb.server.types.value.Value; import com.foundationdb.server.types.value.ValueSource; import com.foundationdb.server.types.value.ValueSources; import com.foundationdb.server.types.texpressions.TValidatedScalar; import com.foundationdb.server.types.texpressions.TValidatedOverload; import com.foundationdb.sql.StandardException; import com.foundationdb.sql.optimizer.plan.*; import com.foundationdb.sql.optimizer.plan.ResultSet.ResultField; import com.foundationdb.sql.optimizer.plan.UpdateStatement.UpdateColumn; import com.foundationdb.sql.optimizer.rule.ConstantFolder.Folder; import com.foundationdb.sql.optimizer.rule.PlanContext.WhiteboardMarker; import com.foundationdb.sql.optimizer.rule.PlanContext.DefaultWhiteboardMarker; import com.foundationdb.sql.parser.CastNode; import com.foundationdb.sql.parser.ValueNode; import com.foundationdb.sql.types.DataTypeDescriptor; import com.foundationdb.sql.types.TypeId; import com.foundationdb.sql.types.CharacterTypeAttributes; import com.foundationdb.util.SparseArray; import com.google.common.base.Objects; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.ArrayList; import java.util.BitSet; import java.util.Collections; import java.util.List; public final class TypeResolver extends BaseRule { private static final Logger logger = LoggerFactory.getLogger(TypeResolver.class); @Override protected Logger getLogger() { return logger; } @Override public void apply(PlanContext plan) { Folder folder = new Folder(plan); ResolvingVisitor resolvingVisitor = new ResolvingVisitor(plan, folder); folder.initResolvingVisitor(resolvingVisitor); plan.putWhiteboard(RESOLVER_MARKER, resolvingVisitor); resolvingVisitor.resolve(plan.getPlan()); new TopLevelCaster(folder, resolvingVisitor.parametersSync).apply(plan.getPlan()); plan.getPlan().accept(ParameterCastInliner.instance); } public static final WhiteboardMarker<ExpressionRewriteVisitor> RESOLVER_MARKER = new DefaultWhiteboardMarker<>(); public static ExpressionRewriteVisitor getResolver(PlanContext plan) { return plan.getWhiteboard(RESOLVER_MARKER); } public static class ResolvingVisitor implements PlanVisitor, ExpressionRewriteVisitor { private Folder folder; private TypesRegistryService registry; private TypesTranslator typesTranslator; private QueryContext queryContext; private ParametersSync parametersSync; public ResolvingVisitor(PlanContext context, Folder folder) { this.folder = folder; SchemaRulesContext src = (SchemaRulesContext)context.getRulesContext(); registry = src.getTypesRegistry(); typesTranslator = src.getTypesTranslator(); parametersSync = new ParametersSync(registry.getCastsResolver()); this.queryContext = context.getQueryContext(); } public void resolve(PlanNode root) { root.accept(this); parametersSync.updateTypes(typesTranslator); } @Override public boolean visitChildrenFirst(ExpressionNode n) { return true; } @Override public boolean visitEnter(PlanNode n) { return visit(n); } @Override public boolean visitLeave(PlanNode n) { if (n instanceof ResultSet) { updateResultFields(n, ((ResultSet)n).getFields()); } else if (n instanceof DMLStatement) { updateResultFields(n, ((DMLStatement)n).getResultField()); } else if (n instanceof ExpressionsSource) { handleExpressionsSource((ExpressionsSource)n); } else if( n instanceof SetPlanNode){ updateSetNode((SetPlanNode)n); } return true; } private void updateResultFields(PlanNode n, List<ResultField> rsFields) { if (rsFields == null) return; TypedPlan typedInput = findTypedPlanNode(n); if (typedInput != null) { assert rsFields.size() == typedInput.nFields() : rsFields + " not applicable to " + typedInput; for (int i = 0, size = rsFields.size(); i < size; i++) { ResultField rsField = rsFields.get(i); rsField.setType(typedInput.getTypeAt(i)); } } else { logger.warn("no Project node found for result fields: {}", n); } } private TypedPlan findTypedPlanNode(PlanNode n) { while (true) { if (n instanceof TypedPlan) return (TypedPlan) n; if ( (n instanceof ResultSet) || (n instanceof DMLStatement) || (n instanceof Select) || (n instanceof Sort) || (n instanceof Limit) || (n instanceof Distinct)) n = ((BasePlanWithInput)n).getInput(); else return null; } } @Override public boolean visit(PlanNode n) { return true; } @Override public ExpressionNode visit(ExpressionNode n) { if (n instanceof CastExpression) n = handleCastExpression((CastExpression) n); else if (n instanceof FunctionExpression) n = handleFunctionExpression((FunctionExpression) n); else if (n instanceof IfElseExpression) n = handleIfElseExpression((IfElseExpression) n); else if (n instanceof AggregateFunctionExpression) n = handleAggregateFunctionExpression((AggregateFunctionExpression) n); else if (n instanceof ExistsCondition) n = handleExistsCondition((ExistsCondition) n); else if (n instanceof SubqueryValueExpression) n = handleSubqueryValueExpression((SubqueryValueExpression) n); else if (n instanceof SubqueryResultSetExpression) n = handleSubqueryResultSetExpression((SubqueryResultSetExpression) n); else if (n instanceof AnyCondition) n = handleAnyCondition((AnyCondition) n); else if (n instanceof ComparisonCondition) n = handleComparisonCondition((ComparisonCondition) n); else if (n instanceof ColumnExpression) n = handleColumnExpression((ColumnExpression) n); else if (n instanceof InListCondition) n = handleInListCondition((InListCondition) n); else if (n instanceof ParameterCondition) n = handleParameterCondition((ParameterCondition) n); else if (n instanceof ParameterExpression) n = handleParameterExpression((ParameterExpression) n); else if (n instanceof BooleanOperationExpression) n = handleBooleanOperationExpression((BooleanOperationExpression) n); else if (n instanceof BooleanConstantExpression) n = handleBooleanConstantExpression((BooleanConstantExpression) n); else if (n instanceof ConstantExpression) n = handleConstantExpression((ConstantExpression) n); else if (n instanceof RoutineExpression) n = handleRoutineExpression((RoutineExpression) n); else if (n instanceof ColumnDefaultExpression) n = handleColumnDefaultExpression((ColumnDefaultExpression) n); else logger.warn("unrecognized ExpressionNode subclass: {}", n.getClass()); n = folder.foldConstants(n); // Set nullability of TInstance if it hasn't been given explicitly // At the same time, update the node's DataTypeDescriptor to match its TInstance TPreptimeValue tpv = n.getPreptimeValue(); if (tpv != null) { TInstance type = tpv.type(); if ((n.getSQLtype() != null) && (n.getSQLtype().getCharacterAttributes() != null) && (n.getSQLtype().getCharacterAttributes().getCollationDerivation() == CharacterTypeAttributes.CollationDerivation.EXPLICIT)) { // Apply result of explicit COLLATE, which will otherwise get lost. // No way to mutate the existing instance, so replace entire tpv. type = StringAttribute.copyWithCollation(type, n.getSQLtype().getCharacterAttributes()); tpv = new TPreptimeValue(type, tpv.value()); n.setPreptimeValue(tpv); } if (type != null) { DataTypeDescriptor newDtd = type.dataTypeDescriptor(); n.setSQLtype(newDtd); } } return n; } private void handleExpressionsSource(ExpressionsSource node) { // For each field, we'll fold the instances of that field per row into common types. At the same time, // we'll record on a per-field basis whether any expressions of that field need to be casted (that is, // are not the eventual common type). If so, we'll do the casts in a second pass; if we tried to do them // all in the same path, some fields could end up with unnecessary (and potentially wrong) chained casts. // A null TInstance means an unknown type, which could be a parameter, a literal NULL or of course the // initial fold state. List<List<ExpressionNode>> rows = node.getExpressions(); List<ExpressionNode> firstRow = rows.get(0); int nfields = firstRow.size(); TInstance[] instances = new TInstance[nfields]; BitSet needCasts = new BitSet(nfields); BitSet widened = new BitSet(nfields); // First pass. Assume that instances[f] contains the TInstance of the top operand at field f. This could // be null, if that operand doesn't have a type; this is definitely true of the first row, but it can // also happen if an ExpressionNode is a constant NULL. for (int rownum = 0, expressionsSize = rows.size(); rownum < expressionsSize; rownum++) { List<ExpressionNode> row = rows.get(rownum); assert row.size() == nfields : "jagged rows: " + node; for (int field = 0; field < nfields; ++field) { TInstance botInstance = type(row.get(field)); special: if (botInstance == null) { // type is unknown (parameter or literal NULL), so it doesn't participate in determining a // type, but a cast is needed. needCasts.set(field); // If it is a parameter, it needs to be allowed to be wider than // any of the existing values, while still consistent with them. if (row.get(field) instanceof ParameterExpression) { // Force use of commonTClass(existing,null) below to widen. if (!widened.get(field)) { widened.set(field); break special; } } continue; } else if (instances[field] == null) { // Take type from first non-NULL, unless we have to widen, // which commonTClass(null,expr) will take care of. if (widened.get(field)) { break special; } instances[field] = botInstance; continue; } // If the two are the same, we know we don't need to cast them. // This logic also handles the case where both are null, which is not a valid argument // to resolver.commonTClass. if (Objects.equal(instances[field], botInstance)) continue; TClass topClass = tclass(instances[field]); TClass botClass = tclass(botInstance); TClass commonTClass = registry.getCastsResolver().commonTClass(topClass, botClass); if (commonTClass == null) { throw new AkibanInternalException("no common type found found between row " + (rownum-1) + " and " + rownum + " at field " + field); } // The two rows have different TClasses at this index, so we'll need at least one of them to // be casted. Also the common class will be the widest comparable. needCasts.set(field); widened.set(field); boolean eitherIsNullable; if (botInstance == null) eitherIsNullable = true; else eitherIsNullable = botInstance.nullability(); if ( (!eitherIsNullable) && (instances[field] != null)) { // bottom is not nullable, and there is a top. See if it's nullable eitherIsNullable = instances[field].nullability(); } // need to set a new instances[field]. Rules: // - if topClass and botClass are the same as common, use picking algorithm // - else, if one of them == commonTClass, use topInstance or botInstance (whichever is == common) // - else, use commonTClass.instance() boolean topIsCommon = (topClass == commonTClass); boolean botIsCommon = (botClass == commonTClass); if (topIsCommon && botIsCommon) { // TODO: The special case here for TClass VARCHAR with mismatched charsets // is a limitation of the TClass#pickInstance, as there is no current way // to create a common TInstance for TString with difference charsets. if (commonTClass instanceof TString && botInstance.attribute(StringAttribute.CHARSET) != instances[field].attribute(StringAttribute.CHARSET)) { ; } else { instances[field] = topClass.pickInstance(instances[field], botInstance); } } else if (botIsCommon) { instances[field] = botInstance; } else if (!topIsCommon) { // this of this as "else if (topIsBottom) { <noop> } else { ..." instances[field] = commonTClass.instance(eitherIsNullable); } // See if the top instance is not nullable but should be if (instances[field] != null) { instances[field] = instances[field].withNullable(eitherIsNullable); } } } // See if we need any casts if (!needCasts.isEmpty()) { for (int field = 0; field < nfields; field++) { if (widened.get(field)) { // A parameter should get a really wide VARCHAR so that it // won't be truncated because of other non-parameters. // Also make sure it's VARBINARY, as BINARY means pad, which // we don't want here. TClass tclass = TInstance.tClass(instances[field]); if (tclass instanceof TString) { if (((TString)tclass).getFixedLength() < 0) { instances[field] = typesTranslator.typeClassForString() .instance(Integer.MAX_VALUE, instances[field].attribute(StringAttribute.CHARSET), instances[field].attribute(StringAttribute.COLLATION), instances[field].nullability()); } } else if (tclass instanceof TBinary) { if (((TBinary)tclass).getDefaultLength() < 0) { instances[field] = typesTranslator.typeClassForBinary() .instance(Integer.MAX_VALUE, instances[field].nullability()); } } } } for (List<ExpressionNode> row : rows) { for (int field = 0; field < nfields; ++field) { if (needCasts.get(field) && instances[field] != null) { ExpressionNode orig = row.get(field); ExpressionNode cast = castTo(orig, instances[field], folder, parametersSync); row.set(field, cast); } } } } node.setTInstances(instances); } ExpressionNode handleCastExpression(CastExpression expression) { DataTypeDescriptor dtd = expression.getSQLtype(); TInstance type = typesTranslator.typeForSQLType(dtd); expression.setPreptimeValue(new TPreptimeValue(type)); if (expression.getOperand() instanceof ParameterExpression) { parametersSync.set(expression.getOperand(), type); } return finishCast(expression, folder, parametersSync); } private <V extends TValidatedOverload> ExpressionNode resolve( ResolvableExpression<V> expression, List<ExpressionNode> operands, OverloadResolver<V> resolver, boolean createPreptimeContext) { List<TPreptimeValue> operandClasses = new ArrayList<>(operands.size()); for (ExpressionNode operand : operands) operandClasses.add(operand.getPreptimeValue()); OverloadResult<V> resolutionResult = resolver.get(expression.getFunction(), operandClasses); // cast operands for (int i = 0, operandsSize = operands.size(); i < operandsSize; i++) { TInstance targetType = resolutionResult.getTypeClass(i); if (targetType != null) { ExpressionNode operand = castTo(operands.get(i), targetType, folder, parametersSync); operands.set(i, operand); } } V overload = resolutionResult.getOverload(); expression.setResolved(overload); final List<TPreptimeValue> operandValues = new ArrayList<>(operands.size()); List<TInstance> operandInstances = new ArrayList<>(operands.size()); boolean anyOperandsNullable = false; for (ExpressionNode operand : operands) { TPreptimeValue preptimeValue = operand.getPreptimeValue(); operandValues.add(preptimeValue); operandInstances.add(preptimeValue.type()); if (Boolean.TRUE.equals(preptimeValue.isNullable())) anyOperandsNullable = true; } TOverloadResult overloadResultStrategy = overload.resultStrategy(); TInstance resultInstance; TInstance castTo; TPreptimeContext context; if (createPreptimeContext) { context = new TPreptimeContext(operandInstances, queryContext); expression.setPreptimeContext(context); } else { context = null; } switch (overloadResultStrategy.category()) { case CUSTOM: TInstance castSource = overloadResultStrategy.customRuleCastSource(anyOperandsNullable); if (context == null) context = new TPreptimeContext(operandInstances, queryContext); expression.setPreptimeContext(context); if (castSource == null) { castTo = null; resultInstance = overloadResultStrategy.customRule().resultInstance(operandValues, context); } else { castTo = overloadResultStrategy.customRule().resultInstance(operandValues, context); resultInstance = castSource; } break; case FIXED: resultInstance = overloadResultStrategy.fixed(anyOperandsNullable); castTo = null; break; case PICKING: resultInstance = resolutionResult.getPickedInstance(); castTo = null; break; default: throw new AssertionError(overloadResultStrategy.category()); } if (createPreptimeContext) context.setOutputType(resultInstance); expression.setPreptimeValue(new TPreptimeValue(resultInstance)); ExpressionNode resultExpression; if (castTo == null) { resultExpression = expression; } else { resultExpression = castTo(expression, castTo, folder, parametersSync); resultInstance = castTo; } if (expression instanceof FunctionCondition) { // Didn't know whether function would return boolean or not earlier, // so just assumed it would. if (resultInstance.typeClass() != AkBool.INSTANCE) { castTo = AkBool.INSTANCE.instance(resultInstance.nullability()); resultExpression = castTo(resultExpression, castTo, folder, parametersSync); } } return resultExpression; } ExpressionNode handleFunctionExpression(FunctionExpression expression) { List<ExpressionNode> operands = expression.getOperands(); ExpressionNode result = resolve(expression, operands, registry.getScalarsResolver(), true); TValidatedScalar overload = expression.getResolved(); TPreptimeContext context = expression.getPreptimeContext(); final List<TPreptimeValue> operandValues = new ArrayList<>(operands.size()); for (ExpressionNode operand : operands) { TPreptimeValue preptimeValue = operand.getPreptimeValue(); operandValues.add(preptimeValue); } overload.finishPreptimePhase(context); // Put the preptime value, possibly including nullness, into the expression. The constant folder // will use it. LazyList<TPreptimeValue> lazyInputs = new LazyListBase<TPreptimeValue>() { @Override public TPreptimeValue get(int i) { return operandValues.get(i); } @Override public int size() { return operandValues.size(); } }; TPreptimeValue constantTpv = overload.evaluateConstant(context, overload.filterInputs(lazyInputs)); if (constantTpv != null) { TPreptimeValue oldTpv = expression.getPreptimeValue(); assert oldTpv.type().equals(constantTpv.type()) : oldTpv.type() + " != " + constantTpv.type(); expression.setPreptimeValue(constantTpv); } SparseArray<Object> values = context.getValues(); if ((values != null) && !values.isEmpty()) expression.setPreptimeValues(values); return result; } ExpressionNode handleIfElseExpression(IfElseExpression expression) { ConditionList conditions = expression.getTestConditions(); ExpressionNode thenExpr = expression.getThenExpression(); ExpressionNode elseExpr = expression.getElseExpression(); // constant-fold if the condition is constant if (conditions.size() == 1) { ValueSource conditionVal = pval(conditions.get(0)); if (conditionVal != null) { boolean conditionMet = conditionVal.getBoolean(false); return conditionMet ? thenExpr : elseExpr; } } TInstance commonInstance = commonInstance(registry.getCastsResolver(), type(thenExpr), type(elseExpr)); if (commonInstance == null) return ConstantExpression.typedNull(null, null, null); thenExpr = castTo(thenExpr, commonInstance, folder, parametersSync); elseExpr = castTo(elseExpr, commonInstance, folder, parametersSync); expression.setThenExpression(thenExpr); expression.setElseExpression(elseExpr); expression.setPreptimeValue(new TPreptimeValue(commonInstance)); return expression; } ExpressionNode handleAggregateFunctionExpression(AggregateFunctionExpression expression) { List<ExpressionNode> operands = new ArrayList<>(); ExpressionNode operand = expression.getOperand(); if (operand != null) operands.add(operand); ExpressionNode result = resolve(expression, operands, registry.getAggregatesResolver(), false); if (operand != null) expression.setOperand(operands.get(0)); // in case the original operand was casted return result; } ExpressionNode handleExistsCondition(ExistsCondition expression) { return boolExpr(expression, true); } ExpressionNode handleSubqueryValueExpression(SubqueryValueExpression expression) { TypedPlan typedSubquery = findTypedPlanNode(expression.getSubquery().getInput()); TPreptimeValue tpv; assert typedSubquery.nFields() == 1 : typedSubquery; if (typedSubquery instanceof Project) { Project project = (Project) typedSubquery; List<ExpressionNode> projectFields = project.getFields(); assert projectFields.size() == 1 : projectFields; tpv = projectFields.get(0).getPreptimeValue(); } else { tpv = new TPreptimeValue(typedSubquery.getTypeAt(0)); } expression.setPreptimeValue(tpv); return expression; } ExpressionNode handleSubqueryResultSetExpression(SubqueryResultSetExpression expression) { DataTypeDescriptor sqlType = expression.getSQLtype(); if (sqlType.isRowMultiSet()) { setMissingRowMultiSetColumnTypes(sqlType, expression.getSubquery()); } TPreptimeValue tpv = new TPreptimeValue(typesTranslator.typeForSQLType(sqlType)); expression.setPreptimeValue(tpv); return expression; } // If a RowMultiSet column is a function expression, it won't have an SQL type // when the RowMultiSet type is built. Must get it now. static void setMissingRowMultiSetColumnTypes(DataTypeDescriptor sqlType, Subquery subquery) { if (subquery.getInput() instanceof ResultSet) { List<ResultField> fields = ((ResultSet)subquery.getInput()).getFields(); DataTypeDescriptor[] columnTypes = ((TypeId.RowMultiSetTypeId)sqlType.getTypeId()).getColumnTypes(); for (int i = 0; i < columnTypes.length; i++) { if (columnTypes[i] == null) { // TInstance should have been computed earlier in walk. columnTypes[i] = fields.get(i).getSQLtype(); } } } } ExpressionNode handleAnyCondition(AnyCondition expression) { return boolExpr(expression, true); } ExpressionNode handleComparisonCondition(ComparisonCondition expression) { ExpressionNode left = expression.getLeft(); ExpressionNode right = expression.getRight(); TInstance leftTInst = type(left); TInstance rightTInst = type(right); boolean nullable = isNullable(left) || isNullable(right); TKeyComparable keyComparable = registry.getKeyComparable(tclass(leftTInst), tclass(rightTInst)); if (keyComparable != null) { expression.setKeyComparable(keyComparable); } else if (TClass.comparisonNeedsCasting(leftTInst, rightTInst)) { boolean needCasts = true; TCastResolver casts = registry.getCastsResolver(); if ( (left.getClass() == ColumnExpression.class)&& (right.getClass() == ConstantExpression.class)) { // Left is a Column, right is a Constant. Ideally, we'd like to keep the Column as a Column, // and not a CAST(Column AS _) -- otherwise, we can't use it in an index lookup. // So, try to cast the const to the column's type. To do this, CAST(Const -> Column) must be // indexFriendly, *and* casting this result back to the original Const type must equal the same // const. if (rightTInst == null) { // literal null, so a comparison always returns UNKNOWN return new BooleanConstantExpression(null); } if (casts.isIndexFriendly(tclass(leftTInst), tclass(rightTInst))) { TInstance columnType = type(left); TInstance constType = type(right); TCast constToCol = casts.cast(constType, columnType); if (constToCol != null) { TCast colToConst = casts.cast(columnType, constType); if (colToConst != null) { TPreptimeValue constValue = right.getPreptimeValue(); ValueSource asColType = castValue(constToCol, constValue, columnType); TPreptimeValue asColTypeTpv = (asColType == null) ? null : new TPreptimeValue(columnType, asColType); ValueSource backToConstType = castValue(colToConst, asColTypeTpv, constType); if (ValueSources.areEqual(constValue.value(), backToConstType, constType)) { TPreptimeValue constTpv = new TPreptimeValue(columnType, asColType); ConstantExpression constCasted = new ConstantExpression(constTpv); expression.setRight(constCasted); assert columnType.equals(type(expression.getRight())); needCasts = false; } } } } } if (needCasts) { TInstance common = commonInstance(casts, left, right); if (common == null) { // TODO this means we have something like '? = ?' or '? = NULL'. What to do? Varchar for now? common = typesTranslator.typeForString(); } left = castTo(left, common, folder, parametersSync); right = castTo(right, common, folder, parametersSync); expression.setLeft(left); expression.setRight(right); } } return boolExpr(expression, nullable); } private boolean isNullable(ExpressionNode node) { TInstance type = type(node); return type == null || type.nullability(); } ExpressionNode handleColumnExpression(ColumnExpression expression) { Column column = expression.getColumn(); ColumnSource columnSource = expression.getTable(); if (column != null) { assert columnSource instanceof TableSource : columnSource; TInstance columnInstance = column.getType(); if ((Boolean.FALSE == columnInstance.nullability()) && (expression.getSQLtype() != null) && (expression.getSQLtype().isNullable())) { // With an outer join, the column can still be nullable. columnInstance = columnInstance.withNullable(true); } expression.setPreptimeValue(new TPreptimeValue(columnInstance)); } else if (columnSource instanceof AggregateSource) { AggregateSource aggTable = (AggregateSource) columnSource; TPreptimeValue ptv = aggTable.getField(expression.getPosition()).getPreptimeValue(); expression.setPreptimeValue(ptv); } else if (columnSource instanceof SubquerySource) { TPreptimeValue tpv; Subquery subquery = ((SubquerySource)columnSource).getSubquery(); TypedPlan typedSubquery = findTypedPlanNode(subquery.getInput()); if (typedSubquery != null) { tpv = new TPreptimeValue(typedSubquery.getTypeAt(expression.getPosition())); } else { logger.warn("no Project found for subquery: {}", columnSource); tpv = new TPreptimeValue(typesTranslator.typeForSQLType(expression.getSQLtype())); } expression.setPreptimeValue(tpv); return expression; } else if (columnSource instanceof NullSource) { expression.setPreptimeValue(new TPreptimeValue(null, null)); return expression; } else if (columnSource instanceof Project) { Project pTable = (Project) columnSource; TPreptimeValue ptv = pTable.getFields().get(expression.getPosition()).getPreptimeValue(); expression.setPreptimeValue(ptv); } else if (columnSource instanceof ExpressionsSource) { ExpressionsSource exprsTable = (ExpressionsSource) columnSource; List<List<ExpressionNode>> expressions = exprsTable.getExpressions(); TPreptimeValue tpv; if (expressions.size() == 1) { // get the TPV straight from the expression, since there's just one row tpv = expressions.get(0).get(expression.getPosition()).getPreptimeValue(); } else { TInstance type = exprsTable.getTypeAt(expression.getPosition()); tpv = new TPreptimeValue(type); } expression.setPreptimeValue(tpv); } else if (columnSource instanceof CreateAs){ expression.setPreptimeValue(new TPreptimeValue(null, null)); return expression; } else { throw new AssertionError(columnSource + "(" + columnSource.getClass() + ")"); } return expression; } ExpressionNode handleInListCondition(InListCondition expression) { boolean nullable = isNullable(expression.getOperand()); if (!nullable) { List<ExpressionNode> expressions = expression.getExpressions(); for (int i = 0, expressionsSize = expressions.size(); (!nullable) && i < expressionsSize; i++) { ExpressionNode rhs = expressions.get(i); nullable = isNullable(rhs); } } return boolExpr(expression, nullable); } ExpressionNode handleParameterCondition(ParameterCondition expression) { parametersSync.uninferred(expression); TInstance type = AkBool.INSTANCE.instance(true); return castTo(expression, type, folder, parametersSync); } ExpressionNode handleParameterExpression(ParameterExpression expression) { parametersSync.uninferred(expression); return expression; } ExpressionNode handleBooleanOperationExpression(BooleanOperationExpression expression) { boolean isNullable; DataTypeDescriptor sqLtype = expression.getSQLtype(); isNullable = sqLtype == null // TODO if no SQL type, assume nullable for now || sqLtype.isNullable(); // TODO rely on the previous type computer for now return boolExpr(expression, isNullable); } ExpressionNode handleBooleanConstantExpression(BooleanConstantExpression expression) { return boolExpr(expression, expression.isNullable()); } ExpressionNode handleConstantExpression(ConstantExpression expression) { // will be lazily loaded as necessary return expression; } ExpressionNode handleRoutineExpression(RoutineExpression expression) { Routine routine = expression.getRoutine(); List<ExpressionNode> operands = expression.getOperands(); for (int i = 0; i < operands.size(); i++) { ExpressionNode operand = castTo(operands.get(i), routine.getParameters().get(i).getType(), folder, parametersSync); operands.set(i, operand); } TPreptimeValue tpv = new TPreptimeValue(routine.getReturnValue().getType()); expression.setPreptimeValue(tpv); return expression; } ExpressionNode handleColumnDefaultExpression(ColumnDefaultExpression expression) { if (expression.getPreptimeValue() == null) { TPreptimeValue tpv = new TPreptimeValue(expression.getColumn().getType()); expression.setPreptimeValue(tpv); } return expression; } private static ValueSource pval(ExpressionNode expression) { return expression.getPreptimeValue().value(); } private void updateSetNode(SetPlanNode setPlan) { ProjectHolder leftProject = getProject(setPlan.getLeft()); ProjectHolder rightProject= getProject(setPlan.getRight()); Project topProject = (Project)setPlan.getOutput(); ResultSet leftResult = leftProject.getResultSet(); ResultSet rightResult = rightProject.getResultSet(); int nFields = leftProject.getFields().size(); List<ResultField> fields = new ArrayList<>(nFields); for (int i= 0; i < nFields; i++) { ExpressionNode leftExpr = leftProject.getFields().get(i); ExpressionNode rightExpr= rightProject.getFields().get(i); DataTypeDescriptor leftType = leftExpr.getSQLtype(); DataTypeDescriptor rightType = rightExpr.getSQLtype(); DataTypeDescriptor projectType = null; // Case of SELECT null UNION SELECT null -> pick a type if (leftType == null && rightType == null) projectType = new DataTypeDescriptor (TypeId.VARCHAR_ID, true); if (leftType == null) projectType = rightType; else if (rightType == null) projectType = leftType; else { try { projectType = leftType.getDominantType(rightType); } catch (StandardException e) { projectType = null; } } TInstance projectInst = typesTranslator.typeForSQLType(projectType); leftProject.applyCast(i, projectType, projectInst); rightProject.applyCast(i, projectType, projectInst); ResultField leftField = leftResult.getFields().get(i); ResultField rightField = rightResult.getFields().get(i); String name = null; if (leftField.getName() != null && rightField.getName() != null) name = leftField.getName(); else if (leftField.getName() != null) name = leftField.getName(); else if (rightField.getName() != null) name = rightField.getName(); Column column = null; // If both side of the setPlan reference the same column, use it, else null if (leftField.getColumn() != null && rightField.getColumn() != null && leftField.getColumn() == rightField.getColumn()) column = leftField.getColumn(); fields.add(new ResultField(name, projectType, column)); fields.get(i).setType(typesTranslator.typeForSQLType(projectType)); } setPlan.setResults(fields); // setPlan -> project -> ResultSet if (setPlan.getOutput().getOutput() instanceof ResultSet) { ResultSet rs = (ResultSet)setPlan.getOutput().getOutput(); ResultSet newSet = new ResultSet (setPlan, fields); rs.getOutput().replaceInput(rs, newSet); } } private void castProjectField (CastExpression cast, Folder folder, ParametersSync parameterSync, TypesTranslator typesTranslator) { DataTypeDescriptor dtd = cast.getSQLtype(); TInstance type = typesTranslator.typeForSQLType(dtd); cast.setPreptimeValue(new TPreptimeValue(type)); TypeResolver.finishCast(cast, folder, parameterSync); } private ProjectHolder getProject(PlanNode node) { PlanNode project = ((BasePlanWithInput)node).getInput(); if (project instanceof Project) return new SingleProjectHolder((Project)project); else if (project instanceof SetPlanNode) { return new SetProjectHolder((SetPlanNode)project); } else if (!(project instanceof BasePlanWithInput)) return null; project = ((BasePlanWithInput)project).getInput(); if (project instanceof Project) return new SingleProjectHolder((Project)project); return null; } private static interface ProjectHolder { ResultSet getResultSet(); List<ExpressionNode> getFields(); void applyCast(int i, DataTypeDescriptor projectType, TInstance projectInstance); } private class SetProjectHolder implements ProjectHolder { private ProjectHolder leftProject; private ProjectHolder rightProject; private ResultSet resultSet; private SetProjectHolder(SetPlanNode node) { resultSet = (ResultSet)node.getOutput(); leftProject = getProject(node.getLeft()); rightProject = getProject(node.getRight()); } @Override public ResultSet getResultSet() { return resultSet; } @Override public List<ExpressionNode> getFields() { return leftProject.getFields(); } @Override public void applyCast(int i, DataTypeDescriptor projectType, TInstance projectInstance) { leftProject.applyCast(i, projectType, projectInstance); rightProject.applyCast(i, projectType, projectInstance); } } private class SingleProjectHolder implements ProjectHolder { private Project project; private SingleProjectHolder(Project project) { this.project = project; } @Override public ResultSet getResultSet() { return (ResultSet)project.getOutput(); } @Override public List<ExpressionNode> getFields() { return project.getFields(); } @Override public void applyCast(int i, DataTypeDescriptor projectType, TInstance projectInstance) { ExpressionNode expression = getFields().get(i); TInstance expressionType = type(expression); if (expression instanceof CastExpression) { if (expressionType == null) { CastExpression castExpression = (CastExpression) expression; expression = castExpression.getOperand(); expressionType = type(expression); } } if (expressionType == null || !expressionType.equals(projectInstance)) { ValueNode source = expression.getSQLsource(); CastExpression cast = new CastExpression(expression, projectType, source, projectInstance); castProjectField(cast, folder, parametersSync, typesTranslator); getFields().set(i, cast); } } } } private static ValueSource castValue(TCast cast, TPreptimeValue source, TInstance targetInstance) { if (source == null) return null; boolean targetsMatch = targetInstance.typeClass() == cast.targetClass(); boolean sourcesMatch = source.type().typeClass() == cast.sourceClass(); if ( (!targetsMatch) || (!sourcesMatch) ) throw new IllegalArgumentException("cast <" + cast + "> not applicable to CAST(" + source + " AS " + targetInstance); TExecutionContext context = new TExecutionContext( null, Collections.singletonList(source.type()), targetInstance, null, // TODO ErrorHandlingMode.ERROR, ErrorHandlingMode.ERROR, ErrorHandlingMode.ERROR ); Value result = new Value(targetInstance); try { cast.evaluate(context, source.value(), result); } catch (Exception e) { if (logger.isTraceEnabled()) { logger.trace("while casting values " + source + " to " + targetInstance + " using " + cast, e); } result = null; } return result; } private static ExpressionNode boolExpr(ExpressionNode expression, boolean nullable) { TInstance type = AkBool.INSTANCE.instance(nullable); ValueSource value = null; if (expression.getPreptimeValue() != null) { if (type.equals(expression.getPreptimeValue().type())) return expression; value = expression.getPreptimeValue().value(); } expression.setPreptimeValue(new TPreptimeValue(type, value)); return expression; } static class TopLevelCaster { private List<? extends ColumnContainer> targetColumns; private Folder folder; private ParametersSync parametersSync; TopLevelCaster(Folder folder, ParametersSync parametersSync) { this.folder = folder; this.parametersSync = parametersSync; } public void apply(PlanNode node) { while (targetColumns == null) { if (node instanceof InsertStatement) { InsertStatement insert = (InsertStatement) node; setTargets(insert.getTargetColumns()); } else if (node instanceof UpdateStatement) { UpdateStatement update = (UpdateStatement) node; setTargets(update.getUpdateColumns()); for (UpdateColumn updateColumn : update.getUpdateColumns()) { Column target = updateColumn.getColumn(); ExpressionNode value = updateColumn.getExpression(); ExpressionNode casted = castTo(value, target.getType(), folder, parametersSync); if (casted != value) { updateColumn.setExpression(casted); } } } if (node instanceof BasePlanWithInput) node = ((BasePlanWithInput)node).getInput(); else break; } if (targetColumns != null) { if (node instanceof Project) handleProject((Project) node); else if (node instanceof ExpressionsSource) handleExpressionSource((ExpressionsSource) node); } } private void handleExpressionSource(ExpressionsSource source) { for (List<ExpressionNode> row : source.getExpressions()) { castToTarget(row, source); } } private void castToTarget(List<ExpressionNode> row, TypedPlan plan) { for (int i = 0, ncols = row.size(); i < ncols; ++i) { Column target = targetColumns.get(i).getColumn(); ExpressionNode column = row.get(i); ExpressionNode casted = castTo(column, target.getType(), folder, parametersSync); row.set(i, casted); plan.setTypeAt(i, casted.getPreptimeValue()); } } private void handleProject(Project source) { castToTarget(source.getFields(), source); } private void setTargets(List<? extends ColumnContainer> targetColumns) { assert this.targetColumns == null : this.targetColumns; this.targetColumns = targetColumns; } } private static class ParameterCastInliner implements PlanVisitor, ExpressionRewriteVisitor { private static final ParameterCastInliner instance = new ParameterCastInliner(); // ExpressionRewriteVisitor @Override public ExpressionNode visit(ExpressionNode n) { if (n instanceof CastExpression) { CastExpression cast = (CastExpression) n; ExpressionNode operand = cast.getOperand(); if (operand instanceof ParameterExpression) { TInstance castTarget = type(cast); TInstance parameterType = type(operand); if (castTarget != null && castTarget.equals(parameterType)) n = operand; } } return n; } @Override public boolean visitChildrenFirst(ExpressionNode n) { return false; } // PlanVisitor @Override public boolean visitEnter(PlanNode n) { return true; } @Override public boolean visitLeave(PlanNode n) { return true; } @Override public boolean visit(PlanNode n) { return true; } } private static ExpressionNode castTo(ExpressionNode expression, TInstance targetInstance, Folder folder, ParametersSync parametersSync) { // parameters and literal nulls have no type, so just set the type -- they'll be polymorphic about it. if (expression instanceof ParameterExpression) { targetInstance = targetInstance.withNullable(true); CastExpression castExpression = newCastExpression(expression, targetInstance); castExpression.setPreptimeValue(new TPreptimeValue(targetInstance)); parametersSync.set(expression, targetInstance); return castExpression; } if (expression instanceof NullSource) { ValueSource nullSource = ValueSources.getNullSource(targetInstance); expression.setPreptimeValue(new TPreptimeValue(targetInstance, nullSource)); return expression; } if (equalForCast(targetInstance, type(expression))) return expression; DataTypeDescriptor sqlType = expression.getSQLtype(); targetInstance = targetInstance.withNullable(sqlType == null || sqlType.isNullable()); CastExpression castExpression = newCastExpression(expression, targetInstance); castExpression.setPreptimeValue(new TPreptimeValue(targetInstance)); ExpressionNode result = finishCast(castExpression, folder, parametersSync); result = folder.foldConstants(result); return result; } private static boolean equalForCast(TInstance target, TInstance source) { if (source == null) return false; if (!target.typeClass().equals(source.typeClass())) return false; if (target.typeClass() instanceof TString) { // Operations between strings do not require that the // charsets / collations be the same. return (target.attribute(StringAttribute.MAX_LENGTH) == source.attribute(StringAttribute.MAX_LENGTH)); } return target.equalsExcludingNullable(source); } private static CastExpression newCastExpression(ExpressionNode expression, TInstance targetInstance) { if (targetInstance.typeClass() == AkBool.INSTANCE) // Allow use as a condition. return new BooleanCastExpression(expression, targetInstance.dataTypeDescriptor(), expression.getSQLsource(), targetInstance); else return new CastExpression(expression, targetInstance.dataTypeDescriptor(), expression.getSQLsource(), targetInstance); } protected static ExpressionNode finishCast(CastExpression castNode, Folder folder, ParametersSync parametersSync) { // If we have something like CAST( (VALUE[n] of ExpressionsSource) to FOO ), // refactor it to VALUE[n] of ExpressionsSource2, where ExpressionsSource2 has columns at n cast to FOO. ExpressionNode inner = castNode.getOperand(); ExpressionNode result = castNode; if (inner instanceof ColumnExpression) { ColumnExpression columnNode = (ColumnExpression) inner; ColumnSource source = columnNode.getTable(); if (source instanceof ExpressionsSource) { ExpressionsSource expressionsTable = (ExpressionsSource) source; List<List<ExpressionNode>> rows = expressionsTable.getExpressions(); int pos = columnNode.getPosition(); TInstance castType = castNode.getType(); for (int i = 0, nrows = rows.size(); i < nrows; ++i) { List<ExpressionNode> row = rows.get(i); ExpressionNode targetColumn = row.get(pos); targetColumn = castTo(targetColumn, castType, folder, parametersSync); row.set(pos, targetColumn); } result = columnNode; result.setPreptimeValue(castNode.getPreptimeValue()); expressionsTable.getFieldTInstances()[pos] = castType; } if(source instanceof CreateAs) { inner.setPreptimeValue(castNode.getPreptimeValue()); } } return result; } private static TClass tclass(ExpressionNode operand) { return tclass(type(operand)); } private static TClass tclass(TInstance type) { return (type == null) ? null : type.typeClass(); } private static TInstance type(ExpressionNode node) { TPreptimeValue ptv = node.getPreptimeValue(); return ptv == null ? null : ptv.type(); } private static TInstance commonInstance(TCastResolver resolver, ExpressionNode left, ExpressionNode right) { return commonInstance(resolver, type(left), type(right)); } public static TInstance commonInstance(TCastResolver resolver, TInstance left, TInstance right) { if (left == null && right == null) return null; else if (left == null) return right; else if (right == null) return left; TClass leftTClass = left.typeClass(); TClass rightTClass = right.typeClass(); if (leftTClass == rightTClass) return leftTClass.pickInstance(left, right); TClass commonClass = resolver.commonTClass(leftTClass, rightTClass); if (commonClass == null) throw error("couldn't determine a type for CASE expression"); if (commonClass == leftTClass) return left; if (commonClass == rightTClass) return right; return commonClass.instance(left.nullability() || right.nullability()); } private static RuntimeException error(String message) { throw new RuntimeException(message); // TODO what actual error type? } /** * Helper class for keeping various instances of the same parameter in sync, in terms of their TInstance. So for * instance, in an expression IF($0 == $1, $1, $0) we'd want both $0s to have the same TInstance, and ditto for * both $1s. */ protected static class ParametersSync { private TCastResolver resolver; private SparseArray<List<ExpressionNode>> instancesMap; public ParametersSync(TCastResolver resolver) { this.resolver = resolver; this.instancesMap = new SparseArray<>(); } public void uninferred(ParameterExpression parameterExpression) { //assert parameterExpression.getPreptimeValue() == null : parameterExpression; TPreptimeValue preptimeValue; List<ExpressionNode> siblings = siblings(parameterExpression); if (siblings.isEmpty()) { preptimeValue = new TPreptimeValue(); if (parameterExpression.getSQLsource() != null) // Start with type client intends to send, if any. preptimeValue.type((TInstance) parameterExpression.getSQLsource().getUserData()); parameterExpression.setPreptimeValue(new TPreptimeValue()); } else { preptimeValue = siblings.get(0).getPreptimeValue(); } parameterExpression.setPreptimeValue(preptimeValue); siblings.add(parameterExpression); } private List<ExpressionNode> siblings(ParameterExpression parameterNode) { int pos = parameterNode.getPosition(); List<ExpressionNode> siblings = instancesMap.get(pos); if (siblings == null) { siblings = new ArrayList<>(4); // guess at capacity. this should be plenty instancesMap.set(pos, siblings); } return siblings; } public void set(ExpressionNode node, TInstance type) { List<ExpressionNode> siblings = siblings((ParameterExpression) node); TPreptimeValue sharedTpv = siblings.get(0).getPreptimeValue(); TInstance previousInstance = sharedTpv.type(); type = commonInstance(resolver, type, previousInstance); sharedTpv.type(type); } public void updateTypes(TypesTranslator typesTranslator) { int nparams = instancesMap.lastDefinedIndex(); for (int i = 0; i < nparams; i++) { if (!instancesMap.isDefined(i)) continue; List<ExpressionNode> siblings = instancesMap.get(i); TPreptimeValue sharedTpv = siblings.get(0).getPreptimeValue(); TInstance type = sharedTpv.type(); DataTypeDescriptor sqlType = null; if (type == null) { sqlType = siblings.get(0).getSQLtype(); if (sqlType != null) type = typesTranslator.typeForSQLType(sqlType); else type = typesTranslator.typeClassForString().instance(true); sharedTpv.type(type); } if (sqlType == null) sqlType = type.dataTypeDescriptor(); for (ExpressionNode param : siblings) { param.setSQLtype(sqlType); if (param.getSQLsource() != null) { try { param.getSQLsource().setType(sqlType); param.getSQLsource().setUserData(type); } catch (StandardException ex) { throw new SQLParserInternalException(ex); } } } } } } }
package com.redhat.ceylon.compiler.typechecker.tree; import java.util.ArrayList; import java.util.List; import org.antlr.runtime.Token; public class CustomTree extends Tree { public static class AttributeDeclaration extends Tree.AttributeDeclaration { public AttributeDeclaration(Token token) { super(token); } @Override public void visit(Visitor visitor) { if (visitor instanceof NaturalVisitor) { super.visit(visitor); } else { if (getSpecifierOrInitializerExpression()!=null) getSpecifierOrInitializerExpression().visit(visitor); super.visit(visitor); } } @Override public void visitChildren(Visitor visitor) { if (visitor instanceof NaturalVisitor) { super.visitChildren(visitor); } else { Walker.walkAnyAttribute(visitor, this); } } @Override public String getNodeType() { return AttributeDeclaration.class.getSimpleName(); } } public static class MethodDeclaration extends Tree.MethodDeclaration { public MethodDeclaration(Token token) { super(token); } @Override public void visit(Visitor visitor) { if (visitor instanceof NaturalVisitor) { super.visit(visitor); } else { if (getSpecifierExpression()!=null) getSpecifierExpression().visit(visitor); super.visit(visitor); } } @Override public void visitChildren(Visitor visitor) { if (visitor instanceof NaturalVisitor) { super.visitChildren(visitor); } else { if (getTypeParameterList()!=null) getTypeParameterList().visit(visitor); if (getTypeConstraintList()!=null) getTypeConstraintList().visit(visitor); Walker.walkTypedDeclaration(visitor, this); for (ParameterList subnode: getParameterLists()) subnode.visit(visitor); } } @Override public String getNodeType() { return MethodDeclaration.class.getSimpleName(); } } public static class MethodDefinition extends Tree.MethodDefinition { public MethodDefinition(Token token) { super(token); } @Override public void visitChildren(Visitor visitor) { if (visitor instanceof NaturalVisitor) { super.visitChildren(visitor); } else { Walker.walkDeclaration(visitor, this); if (getTypeParameterList()!=null) getTypeParameterList().visit(visitor); if (getTypeConstraintList()!=null) getTypeConstraintList().visit(visitor); if (getType()!=null) getType().visit(visitor); for (ParameterList subnode: getParameterLists()) subnode.visit(visitor); if (getBlock()!=null) getBlock().visit(visitor); } } @Override public String getNodeType() { return MethodDefinition.class.getSimpleName(); } } public static class ClassDefinition extends Tree.ClassDefinition { public ClassDefinition(Token token) { super(token); } @Override public void visitChildren(Visitor visitor) { if (visitor instanceof NaturalVisitor) { Walker.walkDeclaration(visitor, this); if (getTypeParameterList()!=null) getTypeParameterList().visit(visitor); if (getParameterList()!=null) getParameterList().visit(visitor); if (getCaseTypes()!=null) getCaseTypes().visit(visitor); if (getExtendedType()!=null) getExtendedType().visit(visitor); if (getSatisfiedTypes()!=null) getSatisfiedTypes().visit(visitor); if (getTypeConstraintList()!=null) getTypeConstraintList().visit(visitor); if (getClassBody()!=null) getClassBody().visit(visitor); } else { Walker.walkDeclaration(visitor, this); if (getTypeParameterList()!=null) getTypeParameterList().visit(visitor); if (getTypeConstraintList()!=null) getTypeConstraintList().visit(visitor); if (getParameterList()!=null) getParameterList().visit(visitor); if (getCaseTypes()!=null) getCaseTypes().visit(visitor); if (getExtendedType()!=null) getExtendedType().visit(visitor); if (getSatisfiedTypes()!=null) getSatisfiedTypes().visit(visitor); if (getClassBody()!=null) getClassBody().visit(visitor); } } @Override public String getNodeType() { return ClassDefinition.class.getSimpleName(); } } public static class ValueParameterDeclaration extends Tree.ValueParameterDeclaration { public ValueParameterDeclaration(Token token) { super(token); } @Override public void visit(Visitor visitor) { if (visitor instanceof NaturalVisitor) { super.visit(visitor); } else { if (getSpecifierExpression()!=null) getSpecifierExpression().visit(visitor); super.visit(visitor); } } @Override public void visitChildren(Visitor visitor) { if (visitor instanceof NaturalVisitor) { super.visitChildren(visitor); } else { Walker.walkTypedDeclaration(visitor, this); } } @Override public String getNodeType() { return ValueParameterDeclaration.class.getSimpleName(); } } public static class FunctionalParameterDeclaration extends Tree.FunctionalParameterDeclaration { public FunctionalParameterDeclaration(Token token) { super(token); } @Override public void visit(Visitor visitor) { if (visitor instanceof NaturalVisitor) { super.visit(visitor); } else { if (getSpecifierExpression()!=null) getSpecifierExpression().visit(visitor); super.visit(visitor); } } @Override public void visitChildren(Visitor visitor) { if (visitor instanceof NaturalVisitor) { super.visitChildren(visitor); } else { Walker.walkTypedDeclaration(visitor, this); for (ParameterList subnode: getParameterLists()) subnode.visit(visitor); } } @Override public String getNodeType() { return FunctionalParameterDeclaration.class.getSimpleName(); } } public static class UnionType extends Tree.UnionType { public UnionType(Token token) { super(token); } @Override public String getNodeType() { return UnionType.class.getSimpleName(); } @Override protected List<Node> getChildren() { return new ArrayList<Node>(getStaticTypes()); } } public static class IntersectionType extends Tree.IntersectionType { public IntersectionType(Token token) { super(token); } @Override public String getNodeType() { return IntersectionType.class.getSimpleName(); } @Override protected List<Node> getChildren() { return new ArrayList<Node>(getStaticTypes()); } } public static class ExpressionList extends Tree.ExpressionList { public ExpressionList(Token token) { super(token); } @Override public String getNodeType() { return SequencedArgument.class.getSimpleName(); } @Override protected List<Node> getChildren() { return new ArrayList<Node>(getExpressions()); } } public static class CompilationUnit extends Tree.CompilationUnit { public CompilationUnit(Token token) { super(token); } @Override public String getNodeType() { return CompilationUnit.class.getSimpleName(); } @Override protected List<Node> getChildren() { ArrayList<Node> list = new ArrayList<Node>(); list.addAll(super.getChildren()); list.addAll(getDeclarations()); return list; } } public static class ImportList extends Tree.ImportList { public ImportList(Token token) { super(token); } @Override public String getNodeType() { return ImportList.class.getSimpleName(); } @Override protected List<Node> getChildren() { return new ArrayList<Node>(getImports()); } } public static class ExtendedTypeExpression extends Tree.ExtendedTypeExpression { public ExtendedTypeExpression(Token token) { super(token); } @Override public String getNodeType() { return ExtendedTypeExpression.class.getSimpleName(); } public void setExtendedType(SimpleType type) { getChildren().add(type); } } //deliberately don't do this one, so that the span of //a declaration doesn't include its annotations (but //is that really what we want?? /*public static class AnnotationList extends Tree.AnnotationList { public AnnotationList(Token token) { super(token); } @Override public String getNodeType() { return SequencedArgument.class.getSimpleName(); } @Override protected List<Node> getChildren() { return new ArrayList<Node>(getAnnotations()); } }*/ public static class ImportPath extends Tree.ImportPath { public ImportPath(Token token) { super(token); } @Override public String getNodeType() { return ImportPath.class.getSimpleName(); } @Override protected List<Node> getChildren() { return new ArrayList<Node>(getIdentifiers()); } } }
package com.github.horrorho.liquiddonkey.util; import java.util.Objects; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicLong; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * MemMonitor. * <p> * Simple memory monitor, * * @author Ahseya */ public class MemMonitor implements Runnable { private static final Logger logger = LoggerFactory.getLogger(MemMonitor.class); public static MemMonitor from(long intervalMs) { return new MemMonitor(intervalMs, new AtomicLong(0), true); } private final long intervalMs; private final AtomicLong max; private volatile boolean isAlive; MemMonitor(long intervalMs, AtomicLong max, boolean isAlive) { this.intervalMs = intervalMs; this.max = Objects.requireNonNull(max); this.isAlive = isAlive; } @Override public void run() { logger.trace("<< run()"); Runtime runtime = Runtime.getRuntime(); try { while (isAlive) { long usedMb = runtime.totalMemory() - runtime.freeMemory(); long totalMb = runtime.totalMemory(); max.getAndUpdate(current -> usedMb > current ? usedMb : current); logger.debug("-- run() > memory (MB): {} ({}) / {}", usedMb / 1048510, max.get() / 1048510, totalMb / 1048510); TimeUnit.MILLISECONDS.sleep(intervalMs); } } catch (InterruptedException | RuntimeException ex) { logger.warn("-- run() > exception: ", ex); } finally { logger.trace(">> run()"); } } public void kill() { isAlive = false; } public long max() { return max.get(); } }
package com.tisawesomeness.minecord.command.player; import java.io.IOException; import java.util.Arrays; import java.util.HashSet; import java.util.Set; import com.tisawesomeness.minecord.command.Command; import com.tisawesomeness.minecord.database.Database; import com.tisawesomeness.minecord.util.DateUtils; import com.tisawesomeness.minecord.util.MessageUtils; import com.tisawesomeness.minecord.util.NameUtils; import com.tisawesomeness.minecord.util.RequestUtils; import net.dv8tion.jda.core.events.message.MessageReceivedEvent; public class CapeCommand extends Command { //Mojang capes don't want to work, so here's a list of every single UUID with a Mojang cape private static final Set<String> mojangUUIDs = new HashSet<String>(Arrays.asList( "5de530b469bf4b5c953a25819953b16f","ee531ba1534a47209f692605dbf58a10","ad93d7382b674b44984792918b8925f7","34fc1bd64dbd4b37bde6919b9489ed63", "17d349da73ff4e6d94de49d64258d39e","e0a4a12dda4c40fd80096725ed21bfb1","89893e8f920e40a9947afbfdb93effd5","898ed21379b249f98602d1bb03d19ba2", "0b8b22458018456c945d4282121e1b1e","3ce72668b8f9497fbfb4809e47365e17","f96f3d63fc7f46a7964386eb0b3d66cb","c3ddaf580e9849038f13ac91379b2fec", "63b31801739e40579c7a88482c3aacc8","61699b2ed3274a019f1e0ea8c3f06bc6","ed4da3aba7e14b44b91322eb38fdae4b","eb6449ffa3d14fe38e68cec0bf2fc11a", "e9cd1af9615240d7b9574969094e077c","6bef7b0487cf40458cd1fe1ef23c427d","3dba96d4cb25458d83229e7f02cc1ed0","a7ec08830ab449b3acc4cdcf9ab44cf4", "4303c9f77f8842d188565c6be3bd413d","e6b5c088068044df9e1b9bf11792291b","4e1256f5c48d4e4b8dadf248108ee2ee","e3aee364f38e42caa89e5effa8ddbbbd", "1be04a48aaf64eeaaf63845f321bf7af","22cc6d73101f4e1981cc9a985f0aa364","9a22a8e0ba84427698b2fcce2e40eb02","853c80ef3c3749fdaa49938b674adae6", "e540ac6339ee482baba205524d8d7635","d8f9a4340f2d415f9acfcd70341c75ec","4f843993cd424cf59f9ba46237fade57","7125ba8b1c864508b92bb5c042ccfe2b", "6a085b2c19fb4986b453231aa942bbec","d787563cef8b47208654e7f74c4fb0a2","975836b98c114424a08cb6cc3d8b146b","8ecf8beb720c442c911ac9744e65bd9d", "b05881186e75410db2db4d3066b223f7","1c0945aa6853492593f292d3c1693f20","a63d3a672e96461e98b138b2ae2e2a06","c3021db0192c41dfbc8562f7ec51d7ef", "c9b54008fd8047428b238787b5f2401c","61887403c7994288b680d7d5859a20fe","f0fe3b509fee43e2a1656c4526ac6473","82f0dda5507749c29144b3ca655befc1", "0da56a7e1a0d4cd3845dfc2be2559142","f8cdb6839e9043eea81939f85d9c5d69","364beb7e65064a8d8e50569c4ab97eea","069a79f444e94726a5befca90e38aaf5", "ff8f21675ba04d33a84eed78f613d890","4b870d901d2c4bd3a647846757930e2e","36e409d4a16f471d84a0c2d3b87824ad","aaccfbd41145454791e9c3370a4303a7", "0be6054508c8498c8015e9d861f8ce10","0535d36faee643989355a942b4a7f66b","615d08470ddd4bc9a410355a79cdd519","696a82ce41f44b51aa31b8709b8686f0", "6239656ec315456c82b003443cdfb16d","874e749df3224733b49ab1de95b06048","9c2ac9585de945a88ca14122eb4c0b9e","bf2ae63b9cd7406eb3c3d3a3a996cb0f", "1c1bd09a6a0f4928a7914102a35d2670","a5d04fe969ea4f12bf2b7f52172e839b","4e7592ba958644509659e24eb84064ef","6aa836ce053243faa52094efc50fe48c", "93ba87580abd4a3ea009d812d0d22d13","be1fab1b23484bf9a8d527d94a35efa6","d7155343ffae4c8bb654aaecfaa29ed2","b9583ca43e64488a9c8c4ab27e482255", "91f8e3e17c464cd79ff9925c9abd8a3d","3c87f35150c74af992b4de83c34a109a","21d2c289b75f45139f4f85cc9e8c271b","235101390b124101bbcf686fea2e5559", "c30c16fa05e247519f322b6dca5026b3","2a7eee3d6a29498a85cfb53867d95fd7")); public CommandInfo getInfo() { return new CommandInfo( "cape", "Gets the cape of a player.", "<username|uuid> [date]", null, 2000, false, false, true ); } public Result run(String[] args, MessageReceivedEvent e) { long id = e.getGuild().getIdLong(); //No arguments message if (args.length == 0) { String m = ":warning: Incorrect arguments." + "\n" + Database.getPrefix(id) + "cape <username|uuid> [date]" + "\n" + MessageUtils.dateHelp; return new Result(Outcome.WARNING, m, 5); } //Get playername String player = args[0]; String uuid = player; if (player.matches(NameUtils.uuidRegex)) { player = NameUtils.getName(player); //Check for errors if (player == null) { String m = ":x: The Mojang API could not be reached." + "\n" + "Are you sure that UUID exists?"; return new Result(Outcome.WARNING, m, 1.5); } else if (!player.matches(NameUtils.playerRegex)) { String m = ":x: The API responded with an error:\n" + player; return new Result(Outcome.ERROR, m, 3); } } else { //Parse date argument if (args.length > 1) { long timestamp = DateUtils.getTimestamp(Arrays.copyOfRange(args, 1, args.length)); if (timestamp == -1) { return new Result(Outcome.WARNING, MessageUtils.dateErrorString(id, "skin")); } //Get the UUID uuid = NameUtils.getUUID(player, timestamp); } else { uuid = NameUtils.getUUID(player); } //Check for errors if (uuid == null) { String m = ":x: The Mojang API could not be reached." + "\n" + "Are you sure that username exists?" + "\n" + "Usernames are case-sensitive."; return new Result(Outcome.WARNING, m, 2); } else if (!uuid.matches(NameUtils.uuidRegex)) { String m = ":x: The API responded with an error:\n" + uuid; return new Result(Outcome.ERROR, m, 3); } uuid = uuid.replaceAll("-", "").toLowerCase(); } //Fetch capes boolean mc = false; boolean of = false; if (mojangUUIDs.contains(uuid)) { //Mojang cape try { e.getTextChannel().sendFile(RequestUtils.downloadImage("https://minecord.github.io/capes/mojang.png"), "cape.png").queue(); } catch (IOException ex) {} } else { //Minecraft cape try { e.getTextChannel().sendFile(RequestUtils.downloadImage("https://crafatar.com/capes/" + uuid), "cape.png").queue(); } catch (IOException ex) { mc = true; } } //Optifine cape try { e.getTextChannel().sendFile(RequestUtils.downloadImage("http://s.optifine.net/capes/" + player + ".png"), "cape.png").queue(); } catch (IOException ex) { of = true; } if (mc && of) return new Result(Outcome.WARNING, ":warning: " + player + " does not have a cape!"); return new Result(Outcome.SUCCESS); } }
package com.github.moreaunicolas.util; import java.util.function.BiPredicate; import java.util.function.Predicate; import java.util.stream.Stream; public final class ExtendedPredicates { public static <T> Predicate<T> not(Predicate<T> predicate) { return predicate.negate(); } public static <T, U> BiPredicate<T, U> not(BiPredicate<T, U> predicate) { return predicate.negate(); } @SafeVarargs @SuppressWarnings("OptionalGetWithoutIsPresent") // there are at least two predicates public static <T> Predicate<T> or(Predicate<T> first, Predicate<T> second, Predicate<T>... rest) { return stream(first, second, rest).reduce(Predicate::or).get(); } @SafeVarargs @SuppressWarnings("OptionalGetWithoutIsPresent") // there are at least two predicates public static <T, U> BiPredicate<T, U> or(BiPredicate<T, U> first, BiPredicate<T, U> second, BiPredicate<T, U>... rest) { return stream(first, second, rest).reduce(BiPredicate::or).get(); } @SafeVarargs @SuppressWarnings("OptionalGetWithoutIsPresent") // there are at least two predicates public static <T> Predicate<T> and(Predicate<T> first, Predicate<T> second, Predicate<T>... rest) { return stream(first, second, rest).reduce(Predicate::and).get(); } @SafeVarargs @SuppressWarnings("OptionalGetWithoutIsPresent") // there are at least two predicates public static <T, U> BiPredicate<T, U> and(BiPredicate<T, U> first, BiPredicate<T, U> second, BiPredicate<T, U>... rest) { return stream(first, second, rest).reduce(BiPredicate::and).get(); } @SafeVarargs public static <T> Predicate<T> xor(Predicate<T> first, Predicate<T> second, Predicate<T>... rest) { return value -> stream(first, second, rest) .mapToInt(predicate -> predicate.test(value) ? 1 : 0) .sum() == 1; } @SafeVarargs public static <T, U> BiPredicate<T, U> xor(BiPredicate<T, U> first, BiPredicate<T, U> second, BiPredicate<T, U>... rest) { return (a, b) -> stream(first, second, rest) .mapToInt(predicate -> predicate.test(a, b) ? 1 : 0) .sum() == 1; } private static <E> Stream<E> stream(E first, E second, E[] rest) { return Stream.concat(Stream.of(first, second), Stream.of(rest)); } private ExtendedPredicates() { throw new UnsupportedOperationException(); } }
package com.github.stachu540.hirezapi.api; import com.github.stachu540.hirezapi.HiRezAPI; import com.github.stachu540.hirezapi.annotations.Endpoint; import com.github.stachu540.hirezapi.api.rest.RestClient; import com.github.stachu540.hirezapi.enums.DataType; import com.github.stachu540.hirezapi.enums.url.BasePlatform; import com.github.stachu540.hirezapi.exception.SessionException; import com.github.stachu540.hirezapi.models.TestSession; import com.github.stachu540.hirezapi.models.json.CreateSession; import com.github.stachu540.hirezapi.models.json.Model; import lombok.AccessLevel; import lombok.Getter; import lombok.Setter; import org.slf4j.Logger; import java.security.MessageDigest; import java.text.SimpleDateFormat; import java.util.Date; import java.util.SimpleTimeZone; @Getter @Setter public class Authentication <T extends BasePlatform, H extends HiRez<T>>{ private final String DEV_ID; private final String AUTH_KEY; private final Logger logger; private final HiRezSession sessions = new HiRezSession(); @Getter(AccessLevel.NONE) private final H api; private final T platform; private DataType dataType = DataType.JSON; private final RestClient restClient = new RestClient(this); public Authentication(HiRezAPI main, T base_platform, H api) { this.DEV_ID = main.getDevId(); this.AUTH_KEY = main.getAuthKey(); this.platform = base_platform; this.api = api; this.logger = main.getLogger(); } public String getUrl(String endpoint, String... args) { return String.format("%s/%s%s", platform.getUrl(), getEndpoint(endpoint), (args.length > 0) ? "/" + String.join("/", args) : ""); } public boolean hasSessionKey() { return sessions.containsKey(platform) && sessions.get(platform) != null; } <O> O get(String endpoint, Class<O> classModel, String... args) { O objectData = restClient.request(endpoint, classModel, args); if (objectData instanceof Model) { try { Model model = (Model) objectData; if (model.getServerMessage() != null && !endpoint.equals("createsession")) throw new SessionException(model.getServerMessage()); } catch (SessionException e) { e.printStackTrace(); } } return restClient.request(endpoint, classModel, args); } <T extends Model> T get(Class<T> classModel, String... args) { String endpoint = classModel.getDeclaredAnnotation(Endpoint.class).value(); if (endpoint == null) throw new NullPointerException(String.format("Missing annotation value for class: %s [full_path:%s]", classModel.getSimpleName(), classModel.getCanonicalName())); return get(endpoint, classModel, args); } @SuppressWarnings("unchecked") private void createSession() { CreateSession session = api.createSession(); if (session.getRetMsg().equals("Approved")) { sessions.put(platform, session.getSessionId()); } } private boolean testSession() { TestSession session = api.testSession(); return session.isSucessful(); } private String getEndpoint(String endpoint) { String base_endpoint = String.format("%s%s", endpoint, dataType.name().toLowerCase()); switch (endpoint) { case "ping": return base_endpoint; case "createsession": return String.format("%s/%s/%s/%s", base_endpoint, DEV_ID, getSignatue(endpoint), getTimestamp()); default: if (hasSessionKey() && (endpoint.equals("testsession") || testSession())) { return String.format("%s/%s/%s/%s/%s", base_endpoint, DEV_ID, getSignatue(endpoint), sessions.get(platform), getTimestamp()); } else { createSession(); return getEndpoint(endpoint); } } } private String getSignatue(String endpoint) { try { String sig = DEV_ID + endpoint + AUTH_KEY + getTimestamp(); StringBuilder sb = new StringBuilder(); MessageDigest md = MessageDigest.getInstance("MD5"); md.update(sig.getBytes()); byte bytes[] = md.digest(); for (byte bit : bytes) { String hex = Integer.toHexString(0xff & bit); if (hex.length() == 1) sb.append("0"); sb.append(hex); } return sb.toString(); } catch (Exception ex) { ex.printStackTrace(); return null; } } private String getTimestamp() { SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss"); sdf.setTimeZone(new SimpleTimeZone(SimpleTimeZone.UTC_TIME, "UTC")); return sdf.format(new Date()); } }
package org.bouncycastle.crypto.tls; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import org.bouncycastle.crypto.CipherParameters; import org.bouncycastle.crypto.params.AsymmetricKeyParameter; import org.bouncycastle.crypto.params.ECPublicKeyParameters; /** * ECDH key exchange (see RFC 4492) */ class TlsECDHKeyExchange extends TlsECKeyExchange { protected boolean usingFixedAuthentication; TlsECDHKeyExchange(TlsProtocolHandler handler, CertificateVerifyer verifyer, short keyExchange, // TODO Replace with an interface e.g. TlsClientAuth Certificate clientCert, AsymmetricKeyParameter clientPrivateKey) { super(handler, verifyer, keyExchange, clientCert, clientPrivateKey); } public void skipServerCertificate() throws IOException { handler.failWithError(AlertLevel.fatal, AlertDescription.unexpected_message); } public void skipServerKeyExchange() throws IOException { // do nothing } public void processServerKeyExchange(InputStream is, SecurityParameters securityParameters) throws IOException { handler.failWithError(AlertLevel.fatal, AlertDescription.unexpected_message); } public void generateClientKeyExchange(OutputStream os) throws IOException { if (usingFixedAuthentication) { TlsUtils.writeUint24(0, os); } else { generateEphemeralClientKeyExchange((ECPublicKeyParameters)serverPublicKey, os); } } public byte[] generatePremasterSecret() throws IOException { CipherParameters privateKey; if (usingFixedAuthentication) { privateKey = clientPrivateKey; } else { privateKey = clientEphemeralKeyPair.getPrivate(); } return calculateECDHEPreMasterSecret((ECPublicKeyParameters)serverPublicKey, privateKey); } // TODO // public void processServerCertificateRequest(short[] certificateTypes, // Vector certificateAuthorities) // usingFixedAuthentication = false; // boolean fixedAuthenticationOfferedByServer = ecdsaFixedOfferedByServer(certificateTypes); // if (fixedAuthenticationOfferedByServer && clientPrivateKey != null // && serverPublicKey != null && serverPublicKey instanceof ECPublicKeyParameters // && clientPrivateKey instanceof ECPrivateKeyParameters) // ECPublicKeyParameters ecPublicKeyParameters = (ECPublicKeyParameters)serverPublicKey; // ECPrivateKeyParameters ecClientPrivateKey = (ECPrivateKeyParameters)clientPrivateKey; // // TODO Probably the domain parameters need to all be the same? // if (ecPublicKeyParameters.getParameters().getCurve().equals( // ecClientPrivateKey.getParameters().getCurve())) // usingFixedAuthentication = true; // // TODO RSA_fixed_ECDH // public boolean sendCertificateVerify() // return !usingFixedAuthentication; // protected boolean ecdsaFixedOfferedByServer(short[] certificateTypes) // boolean fixedAuthenticationOfferedByServer = false; // for (int i = 0; i < certificateTypes.length; i++) // if (certificateTypes[i] == ClientCertificateType.ecdsa_fixed_ecdh) // fixedAuthenticationOfferedByServer = true; // break; // return fixedAuthenticationOfferedByServer; }
package com.github.tojo.session.cookies; /** * Helper methods for implementing the session-in-a-cookie pattern. * * @author github.com/tojo */ public abstract class SessionInACookie { private static SessionInACookie instance = null; final CipherStrategy cipherStrategy; final SignatureStrategy signatureStrategy; final TimeoutStrategy timeoutStrategy; final BlacklistStrategy blacklistStrategy; /** * Constructor * * @param secret * shared secret for en-/decryption * @param iv * initial vector for en-/decryption * @param cipherStrategy * @param signatureStrategy * @param timeoutStrategy * @param blacklistStrategy */ public SessionInACookie(CipherStrategy cipherStrategy, SignatureStrategy signatureStrategy, TimeoutStrategy timeoutStrategy, BlacklistStrategy blacklistStrategy) { this.cipherStrategy = cipherStrategy; this.signatureStrategy = signatureStrategy; this.timeoutStrategy = timeoutStrategy; this.blacklistStrategy = blacklistStrategy; } /** * Returns the value which has to be stored in the session-in-a-cookie for * the given session data. * * The session data will be prefixed with a unique session id, encryped * through {@link CipherStrategy#encipher(byte[])}, signed by * {@link SignatureStrategy#sign(byte[])} and finally Base64 encoded. * * @param sessionData * the serialized session-in-a-cookie session data * * @return the value of the session-in-a-cookie cookie * @throws CipherStrategyException * if the session data couldn't be encrypted */ public abstract CookieValue encode(SessionData sessionData) throws CipherStrategyException; /** * This method checks the blacklist {@link BlacklistStrategy#check(String)}, * advance the timeout {@link TimeoutStrategy#advance(String)} and decode * the serialized session-in-a-cookie session data. * * @param cookieValue * the value of the session-in-a-cookie cookie * * @return the serialized session-in-a-cookie session data * @throws TimeoutException * if the session has timed out * @throws SignatureException * if the signature is invalid * @throws CipherStrategyException * if the session data couldn't be decrypted * @throws BlacklistException * if the session has been blacklisted * @throws InvalidInputFormatException * if the cookieValue is null or empty */ public abstract byte[] decode(CookieValue cookieValue) throws TimeoutException, SignatureException, BlacklistException; public CipherStrategy getCipherStrategy() { return cipherStrategy; } public SignatureStrategy getSignatureStrategy() { return signatureStrategy; } public TimeoutStrategy getTimeoutStrategy() { return timeoutStrategy; } public BlacklistStrategy getBlacklistStrategy() { return blacklistStrategy; } /** * Get the default {@link SessionInACookie} implementation object. * * @param secret * the shared secret for en- and decryption. * @return the default {@link SessionInACookie} object */ public static SessionInACookie getDefaultInstance(byte[] secret) { // not multi-threading safe if (instance == null) { instance = new SessionInACookieDefaultImpl( new CipherStrategyDefaultImpl(secret), new SignatureStrategyDefaultImpl(secret), new TimeoutStrategyDefaultImpl(), new BlacklistStrategyDefaultImpl()); } return instance; } /** * Get the default {@link SessionInACookie} implementation object. * * @param secret * the shared secret for en- and decryption. * @param timeoutStrategy * @param blacklistStrategy * @return the default {@link SessionInACookie} object */ public static SessionInACookie getDefaultInstance(byte[] secret, TimeoutStrategy timeoutStrategy, BlacklistStrategy blacklistStrategy) { if (instance == null) { instance = new SessionInACookieDefaultImpl( new CipherStrategyDefaultImpl(secret), new SignatureStrategyDefaultImpl(secret), timeoutStrategy, blacklistStrategy); } return instance; } // non-public API static void assertNotNullAndEmpty(byte[] input) { if (input == null || input.length == 0) throw new InvalidInputFormatException( "Input byte[] is null or empty!"); } static void assertMinLength(byte[] input, int minLength) { assertNotNullAndEmpty(input); if (minLength > input.length) throw new InvalidInputFormatException( "Input byte[] is to short! The length must be at least " + minLength); } }
package org.glud.ar; import com.badlogic.gdx.Application; import com.badlogic.gdx.ApplicationAdapter; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.audio.Music; import com.badlogic.gdx.graphics.GL20; import com.badlogic.gdx.graphics.Texture; import com.badlogic.gdx.graphics.g2d.SpriteBatch; import com.badlogic.gdx.math.MathUtils; import com.badlogic.gdx.math.Vector2; public class main extends ApplicationAdapter { final static String TAG = "AR Application"; SpriteBatch batch; Texture img; ARToolKitManager arToolKitManager; Music musica; float volumen; float delta; int marcadorId; Vector2 posicion; public main(ARToolKitManager arToolKitManager){ this.arToolKitManager = arToolKitManager; } @Override public void create () { Gdx.app.setLogLevel(Application.LOG_DEBUG); batch = new SpriteBatch(); img = new Texture("badlogic.jpg"); musica = Gdx.audio.newMusic(Gdx.files.internal("musica.ogg")); musica.setLooping(true); posicion = new Vector2(Gdx.graphics.getWidth()*0.5f - img.getWidth()*0.5f , Gdx.graphics.getHeight()*0.5f - img.getHeight()*0.5f); //cargar macardor // marcadorId = arToolKitManager.cargarMarcador("single;Data/hiro.patt;80"); // Gdx.app.debug(TAG,"Marcador ID = "+marcadorId); // if(marcadorId < 0){ // Gdx.app.error(TAG,"marcador no cargado"); // }else { // Gdx.app.debug(TAG,"marcador cargado"); } @Override public void render () { delta = Gdx.graphics.getDeltaTime(); Gdx.gl.glClearColor(0, 0, 0, 0); Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT); Gdx.app.debug(TAG,"Volumen: "+delta); Gdx.app.debug(TAG,"Volumen: "+volumen); if(arToolKitManager.marcadorVisible(marcadorId)){ if(!musica.isPlaying()) { musica.play(); } if(volumen < 0.99) { volumen += 0.5*delta; musica.setVolume(volumen); } batch.begin(); batch.draw(img,posicion.x,posicion.y); batch.end(); }else{ if(musica.isPlaying()) { volumen -= 0.5*delta; musica.setVolume(volumen); if(volumen < 0.001) { musica.pause(); } } } } @Override public void dispose () { batch.dispose(); img.dispose(); } }
package org.citydb.modules.kml.database; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import javax.vecmath.Point3d; import javax.xml.bind.JAXBException; import net.opengis.kml._2.AltitudeModeEnumType; import net.opengis.kml._2.LineStringType; import net.opengis.kml._2.PlacemarkType; import net.opengis.kml._2.PointType; import org.citydb.api.event.EventDispatcher; import org.citydb.api.geometry.GeometryObject; import org.citydb.api.geometry.GeometryObject.GeometryType; import org.citydb.config.Config; import org.citydb.config.project.kmlExporter.AltitudeOffsetMode; import org.citydb.config.project.kmlExporter.Balloon; import org.citydb.config.project.kmlExporter.ColladaOptions; import org.citydb.config.project.kmlExporter.DisplayForm; import org.citydb.database.adapter.AbstractDatabaseAdapter; import org.citydb.database.adapter.BlobExportAdapter; import org.citydb.log.Logger; import org.citydb.modules.common.balloon.BalloonTemplateHandlerImpl; import org.citydb.modules.common.event.GeometryCounterEvent; public class Transportation extends KmlGenericObject{ public static final String STYLE_BASIS_NAME = "Transportation"; public Transportation(Connection connection, KmlExporterManager kmlExporterManager, net.opengis.kml._2.ObjectFactory kmlFactory, AbstractDatabaseAdapter databaseAdapter, BlobExportAdapter textureExportAdapter, ElevationServiceHandler elevationServiceHandler, BalloonTemplateHandlerImpl balloonTemplateHandler, EventDispatcher eventDispatcher, Config config) { super(connection, kmlExporterManager, kmlFactory, databaseAdapter, textureExportAdapter, elevationServiceHandler, balloonTemplateHandler, eventDispatcher, config); } protected List<DisplayForm> getDisplayForms() { return config.getProject().getKmlExporter().getTransportationDisplayForms(); } public ColladaOptions getColladaOptions() { return config.getProject().getKmlExporter().getTransportationColladaOptions(); } public Balloon getBalloonSettings() { return config.getProject().getKmlExporter().getTransportationBalloon(); } public String getStyleBasisName() { return STYLE_BASIS_NAME; } protected String getHighlightingQuery() { return Queries.getTransportationHighlightingQuery(currentLod); } public void read(KmlSplittingResult work) { PreparedStatement psQuery = null; ResultSet rs = null; boolean reversePointOrder = false; try { int lodToExportFrom = config.getProject().getKmlExporter().getLodToExportFrom(); currentLod = lodToExportFrom == 5 ? 4: lodToExportFrom; int minLod = lodToExportFrom == 5 ? 0: lodToExportFrom; while (currentLod >= minLod) { if(!work.getDisplayForm().isAchievableFromLoD(currentLod)) break; try { psQuery = connection.prepareStatement(Queries.getTransportationQuery(currentLod, work.getDisplayForm()), ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY); for (int i = 1; i <= psQuery.getParameterMetaData().getParameterCount(); i++) { psQuery.setLong(i, work.getId()); } rs = psQuery.executeQuery(); if (rs.isBeforeFirst()) { break; // result set not empty } else { try { rs.close(); /* release cursor on DB */ } catch (SQLException sqle) {} rs = null; // workaround for jdbc library: rs.isClosed() throws SQLException! try { psQuery.close(); /* release cursor on DB */ } catch (SQLException sqle) {} } } catch (Exception e2) { try { if (rs != null) rs.close(); } catch (SQLException sqle) {} rs = null; // workaround for jdbc library: rs.isClosed() throws SQLException! try { if (psQuery != null) psQuery.close(); } catch (SQLException sqle) {} } currentLod } if (rs == null) { // result empty, give up String fromMessage = " from LoD" + lodToExportFrom; if (lodToExportFrom == 5) { if (work.getDisplayForm().getForm() == DisplayForm.COLLADA) fromMessage = ". LoD1 or higher required"; else fromMessage = " from any LoD"; } Logger.getInstance().info("Could not display object " + work.getGmlId() + " as " + work.getDisplayForm().getName() + fromMessage + "."); } else { // result not empty kmlExporterManager.updateFeatureTracker(work); // get the proper displayForm (for highlighting) int indexOfDf = getDisplayForms().indexOf(work.getDisplayForm()); if (indexOfDf != -1) { work.setDisplayForm(getDisplayForms().get(indexOfDf)); } if (currentLod == 0) { // LoD0_Network kmlExporterManager.print(createPlacemarksForLoD0Network(rs, work), work, getBalloonSettings().isBalloonContentInSeparateFile()); } else { switch (work.getDisplayForm().getForm()) { case DisplayForm.FOOTPRINT: kmlExporterManager.print(createPlacemarksForFootprint(rs, work), work, getBalloonSettings().isBalloonContentInSeparateFile()); break; case DisplayForm.EXTRUDED: PreparedStatement psQuery2 = connection.prepareStatement(Queries.GET_EXTRUDED_HEIGHT(databaseAdapter.getDatabaseType())); for (int i = 1; i <= psQuery2.getParameterMetaData().getParameterCount(); i++) { psQuery2.setLong(i, work.getId()); } ResultSet rs2 = psQuery2.executeQuery(); rs2.next(); double measuredHeight = rs2.getDouble("envelope_measured_height"); try { rs2.close(); /* release cursor on DB */ } catch (SQLException e) {} try { psQuery2.close(); /* release cursor on DB */ } catch (SQLException e) {} kmlExporterManager.print(createPlacemarksForExtruded(rs, work, measuredHeight, reversePointOrder), work, getBalloonSettings().isBalloonContentInSeparateFile()); break; case DisplayForm.GEOMETRY: setGmlId(work.getGmlId()); setId(work.getId()); if (config.getProject().getKmlExporter().getFilter().isSetComplexFilter()) { // region if (work.getDisplayForm().isHighlightingEnabled()) { kmlExporterManager.print(createPlacemarksForHighlighting(work), work, getBalloonSettings().isBalloonContentInSeparateFile()); } kmlExporterManager.print(createPlacemarksForGeometry(rs, work), work, getBalloonSettings().isBalloonContentInSeparateFile()); } else { // reverse order for single buildings kmlExporterManager.print(createPlacemarksForGeometry(rs, work), work, getBalloonSettings().isBalloonContentInSeparateFile()); // kmlExporterManager.print(createPlacemarkForEachSurfaceGeometry(rs, work.getGmlId(), false)); if (work.getDisplayForm().isHighlightingEnabled()) { // kmlExporterManager.print(createPlacemarkForEachHighlingtingGeometry(work), // work, // getBalloonSetings().isBalloonContentInSeparateFile()); kmlExporterManager.print(createPlacemarksForHighlighting(work), work, getBalloonSettings().isBalloonContentInSeparateFile()); } } break; case DisplayForm.COLLADA: fillGenericObjectForCollada(rs, config.getProject().getKmlExporter().getTransportationColladaOptions().isGenerateTextureAtlases()); String currentgmlId = getGmlId(); setGmlId(work.getGmlId()); setId(work.getId()); if (currentgmlId != work.getGmlId() && getGeometryAmount() > GEOMETRY_AMOUNT_WARNING) { Logger.getInstance().info("Object " + work.getGmlId() + " has more than " + GEOMETRY_AMOUNT_WARNING + " geometries. This may take a while to process..."); } List<Point3d> anchorCandidates = getOrigins(); // setOrigins() called mainly for the side-effect double zOffset = getZOffsetFromConfigOrDB(work.getId()); if (zOffset == Double.MAX_VALUE) { zOffset = getZOffsetFromGEService(work.getId(), anchorCandidates); } setZOffset(zOffset); ColladaOptions colladaOptions = getColladaOptions(); setIgnoreSurfaceOrientation(colladaOptions.isIgnoreSurfaceOrientation()); try { if (work.getDisplayForm().isHighlightingEnabled()) { // kmlExporterManager.print(createPlacemarkForEachHighlingtingGeometry(work), // work, // getBalloonSetings().isBalloonContentInSeparateFile()); kmlExporterManager.print(createPlacemarksForHighlighting(work), work, getBalloonSettings().isBalloonContentInSeparateFile()); } } catch (Exception ioe) { ioe.printStackTrace(); } break; } } } } catch (SQLException sqlEx) { Logger.getInstance().error("SQL error while querying city object " + work.getGmlId() + ": " + sqlEx.getMessage()); return; } catch (JAXBException jaxbEx) { return; } finally { if (rs != null) try { rs.close(); } catch (SQLException e) {} if (psQuery != null) try { psQuery.close(); } catch (SQLException e) {} } } public PlacemarkType createPlacemarkForColladaModel() throws SQLException { // undo trick for very close coordinates double[] originInWGS84 = convertPointCoordinatesToWGS84(new double[] {getOrigin().x, getOrigin().y, getOrigin().z}); setLocation(reducePrecisionForXorY(originInWGS84[0]), reducePrecisionForXorY(originInWGS84[1]), reducePrecisionForZ(originInWGS84[2])); return super.createPlacemarkForColladaModel(); } private List<PlacemarkType> createPlacemarksForLoD0Network(ResultSet rs, KmlSplittingResult work) throws SQLException { DisplayForm footprintSettings = new DisplayForm(DisplayForm.FOOTPRINT, -1, -1); int indexOfDf = getDisplayForms().indexOf(footprintSettings); if (indexOfDf != -1) { footprintSettings = getDisplayForms().get(indexOfDf); } List<PlacemarkType> placemarkList= new ArrayList<PlacemarkType>(); while (rs.next()) { PlacemarkType placemark = kmlFactory.createPlacemarkType(); placemark.setName(work.getGmlId() + "_Transportation_Network"); placemark.setId(/* DisplayForm.FOOTPRINT_PLACEMARK_ID + */ placemark.getName()); if (footprintSettings.isHighlightingEnabled()) placemark.setStyleUrl("#" + getStyleBasisName() + DisplayForm.FOOTPRINT_STR + "Style"); else placemark.setStyleUrl("#" + getStyleBasisName() + DisplayForm.FOOTPRINT_STR + "Normal"); Object buildingGeometryObj = rs.getObject(1); if (!rs.wasNull() && buildingGeometryObj != null) { GeometryObject pointOrCurveGeometry = geometryConverterAdapter.getGeometry(buildingGeometryObj); eventDispatcher.triggerEvent(new GeometryCounterEvent(null, this)); if (pointOrCurveGeometry.getGeometryType() == GeometryType.POINT) { // point double[] ordinatesArray = pointOrCurveGeometry.getCoordinates(0); ordinatesArray = super.convertPointCoordinatesToWGS84(ordinatesArray); PointType point = kmlFactory.createPointType(); point.getCoordinates().add(String.valueOf(reducePrecisionForXorY(ordinatesArray[0]) + "," + reducePrecisionForXorY(ordinatesArray[1]) + "," + reducePrecisionForZ(ordinatesArray[2]))); placemark.setAbstractGeometryGroup(kmlFactory.createPoint(point)); } else { // curve pointOrCurveGeometry = super.convertToWGS84(pointOrCurveGeometry); LineStringType lineString = kmlFactory.createLineStringType(); double zOffset = 0; if (config.getProject().getKmlExporter().getAltitudeOffsetMode().equals(AltitudeOffsetMode.CONSTANT)) { zOffset = config.getProject().getKmlExporter().getAltitudeOffsetValue(); }; for (int i = 0; i < pointOrCurveGeometry.getNumElements(); i++) { double[] ordinatesArray = pointOrCurveGeometry.getCoordinates(i); // order points clockwise for (int j = 0; j < ordinatesArray.length; j = j+3) { lineString.getCoordinates().add(String.valueOf(reducePrecisionForXorY(ordinatesArray[j]) + "," + reducePrecisionForXorY(ordinatesArray[j+1]) + "," + reducePrecisionForZ(ordinatesArray[j+2] + zOffset))); } } lineString.setAltitudeModeGroup(kmlFactory.createAltitudeMode(AltitudeModeEnumType.ABSOLUTE)); placemark.setAbstractGeometryGroup(kmlFactory.createLineString(lineString)); } } // replace default BalloonTemplateHandler with a brand new one, this costs resources! if (getBalloonSettings().isIncludeDescription()) { addBalloonContents(placemark, work.getId()); } placemarkList.add(placemark); } return placemarkList; } }
package org.eclipse.imp.pdb.facts.io; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; import org.eclipse.imp.pdb.facts.IValue; import org.eclipse.imp.pdb.facts.io.binary.BinaryWriter; import org.eclipse.imp.pdb.facts.type.TypeStore; /** * Writer for PDB Binary Files (PBF). * * @author Arnold Lankamp * @deprecated binary writer currently does not support keyword parameters. */ public class BinaryValueWriter implements IValueBinaryWriter{ /** * Constructor. */ public BinaryValueWriter(){ super(); } /** * Writes the given value to the given stream. * * @param value * The value to write. * @param outputStream * The output stream to write to. * @throws IOException * Thrown when something goes wrong. * @see IValueTextWriter#write(IValue, OutputStream) */ public void write(IValue value, OutputStream outputStream) throws IOException{ BinaryWriter binaryWriter = new BinaryWriter(value, outputStream, new TypeStore()); binaryWriter.serialize(); outputStream.flush(); } /** * Writes the given value to the given stream. * * @param value * The value to write. * @param outputStream * The output stream to write to. * @param typeStore * The type store to use. * @throws IOException * Thrown when something goes wrong. * @see IValueTextWriter#write(IValue, OutputStream) */ public void write(IValue value, OutputStream outputStream, TypeStore typeStore) throws IOException{ BinaryWriter binaryWriter = new BinaryWriter(value, outputStream, typeStore); binaryWriter.serialize(); outputStream.flush(); } /** * Writes the given value to a file. * * @param value * The value to write. * @param file * The file to write to. * @param typeStore * The type store to use. * @throws IOException * Thrown when something goes wrong. */ @Deprecated public static void writeValueToFile(IValue value, File file, TypeStore typeStore) throws IOException{ OutputStream fos = null; try{ fos = new BufferedOutputStream(new FileOutputStream(file)); BinaryWriter binaryWriter = new BinaryWriter(value, fos, typeStore); binaryWriter.serialize(); fos.flush(); }finally{ if(fos != null){ fos.close(); } } } }
package com.google.javascript.clutz; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkState; import static com.google.common.collect.Iterables.any; import static com.google.common.collect.Iterables.transform; import static com.google.common.collect.Sets.newHashSet; import static com.google.javascript.rhino.jstype.JSTypeNative.ALL_TYPE; import static com.google.javascript.rhino.jstype.JSTypeNative.ARRAY_TYPE; import static com.google.javascript.rhino.jstype.JSTypeNative.NUMBER_TYPE; import static com.google.javascript.rhino.jstype.JSTypeNative.OBJECT_TYPE; import static com.google.javascript.rhino.jstype.JSTypeNative.STRING_TYPE; import static java.nio.charset.StandardCharsets.UTF_8; import com.google.common.base.Function; import com.google.common.base.Joiner; import com.google.common.base.Preconditions; import com.google.common.base.Predicate; import com.google.common.base.Splitter; import com.google.common.collect.Collections2; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Lists; import com.google.common.collect.Ordering; import com.google.common.collect.Sets; import com.google.common.io.Files; import com.google.javascript.jscomp.AbstractCommandLineRunner; import com.google.javascript.jscomp.Compiler; import com.google.javascript.jscomp.CompilerInput; import com.google.javascript.jscomp.DiagnosticType; import com.google.javascript.jscomp.ErrorFormat; import com.google.javascript.jscomp.SourceFile; import com.google.javascript.jscomp.TypedScope; import com.google.javascript.jscomp.TypedVar; import com.google.javascript.rhino.InputId; import com.google.javascript.rhino.JSDocInfo; import com.google.javascript.rhino.JSDocInfo.Visibility; import com.google.javascript.rhino.JSTypeExpression; import com.google.javascript.rhino.Node; import com.google.javascript.rhino.jstype.EnumElementType; import com.google.javascript.rhino.jstype.EnumType; import com.google.javascript.rhino.jstype.FunctionType; import com.google.javascript.rhino.jstype.JSType; import com.google.javascript.rhino.jstype.JSTypeNative; import com.google.javascript.rhino.jstype.JSTypeRegistry; import com.google.javascript.rhino.jstype.NamedType; import com.google.javascript.rhino.jstype.NoType; import com.google.javascript.rhino.jstype.ObjectType; import com.google.javascript.rhino.jstype.ProxyObjectType; import com.google.javascript.rhino.jstype.RecordType; import com.google.javascript.rhino.jstype.TemplateType; import com.google.javascript.rhino.jstype.TemplatizedType; import com.google.javascript.rhino.jstype.UnionType; import com.google.javascript.rhino.jstype.Visitor; import org.kohsuke.args4j.CmdLineException; import java.io.File; import java.io.IOException; import java.io.StringWriter; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.TreeSet; import java.util.regex.Pattern; import javax.annotation.Nullable; /** * A tool that generates {@code .d.ts} declarations from a Google Closure JavaScript program. */ class DeclarationGenerator { static final String INSTANCE_CLASS_SUFFIX = "_Instance"; /** * Contains symbols that are part of platform externs, but not yet in lib.d.ts This list is * incomplete and will grow as needed. */ private static final Set<String> platformSymbolsMissingInTypeScript = ImmutableSet.of( "Image", "IDBDatabaseException", "RequestCache", "RequestCredentials", "Request", "Headers", "RequestMode", "WorkerLocation", "Promise", "RequestContext", "Response", "ReadableByteStream", "ResponseType", "ReadableStreamController", "CountQueuingStrategy", "ByteLengthQueuingStrategy", "ReadableByteStreamReader", "ReadableStream", "WritableStream", "ReadableStreamReader", "Entry", "DirectoryEntry", "FileSystem", "Metadata", "FileError", "DirectoryReader", "FileEntry", "FileWriter", "FileSaver", "ChromeEvent", "Tab", "ChromeStringArrayEvent", "ChromeStringStringEvent", "ChromeObjectEvent", "ChromeStringEvent", "ChromeBooleanEvent", "MessageSender", "Port"); /** * List of files that are part of closures platform externs. * Not exhaustive, see isPlatformExtern for the rest. */ private static final Set<String> platformExternsFilenames = ImmutableSet.of( "chrome.js", "deprecated.js", "fetchapi.js", "fileapi.js", "flash.js", "google.js", "html5.js", "intl.js", "iphone.js", "mediakeys.js", "mediasource.js", "page_visibility.js", "streamapi.js", "url.js", "v8.js", "webgl.js", "webstorage.js", "whatwg_encoding.js", "window.js"); private static final Set<String> reservedJsWords = ImmutableSet.of( "arguments", "await", "break", "case", "catch", "class", "const", "continue", "debugger", "default", "delete", "do", "else", "enum", "eval", "export", "extends", "false", "finally", "for", "function", "if", "implements", "import", "in", "instanceof", "interface", "let", "new", "null", "package", "private", "protected", "public", "return", "static", "super", "switch", "this", "throw", "true", "try", "typeof", "var", "void", "while", "with", "yield"); /** * List of global platform symbols that are redirected through an alias in closure.lib.d.ts * This allows the following pattern to work: * namespace foo { * class Error extends Error {} * } * by replacing the second Error with GlobalError. */ private static final Set<String> globalSymbolAliases = ImmutableSet.of("Error", "Event"); public static void main(String[] args) { Options options = null; try { options = new Options(args); } catch (CmdLineException e) { System.err.println(e.getMessage()); System.err.println("Usage: clutz [options...] arguments..."); e.getParser().printUsage(System.err); System.err.println(); System.exit(1); } try { DeclarationGenerator generator = new DeclarationGenerator(options); generator.generateDeclarations(); if (generator.hasErrors()) { // Already reported through the print stream. System.exit(2); } } catch (Exception e) { e.printStackTrace(System.err); System.err.println("Uncaught exception in clutz, exiting."); System.exit(3); } System.exit(0); } static final DiagnosticType CLUTZ_MISSING_TYPES = DiagnosticType.error("CLUTZ_MISSING_TYPES", "A dependency does not compile because it is missing some types. This is often caused by " + "the referenced code missing dependencies or by missing externs in your build rule."); private static final Function<Node, String> NODE_GET_STRING = new Function<Node, String>() { @Override public String apply(Node input) { return input.getString(); } }; private final Options opts; private final Compiler compiler; private final ClutzErrorManager errorManager; private StringWriter out = new StringWriter(); /** * If symbols x.y.z and x.y.w exist, childListMap['x.y'] contains the TypedVars for z and w. */ private final HashMap<String, List<TypedVar>> childListMap = new HashMap<>(); /** * Maps types to names for all emitted typedefs, so that further type walks just use the name. * * This is a reverse subset of the private map namesToTypes that Closure keeps in TypeRegistry. * * Currently, this map only contains templatized types and record types. */ private Map<JSType, String> typedefs = new HashMap<>(); /** * Aggregates all emitted types, used in a final pass to find types emitted in type position but * not declared, possibly due to missing goog.provides. */ private final Set<String> typesUsed = new LinkedHashSet<>(); DeclarationGenerator(Options opts) { this.opts = opts; this.compiler = new Compiler(); compiler.disableThreads(); this.errorManager = new ClutzErrorManager(System.err, ErrorFormat.MULTILINE.toFormatter(compiler, true), opts.debug); compiler.setErrorManager(errorManager); } boolean hasErrors() { return errorManager.getErrorCount() > 0; } /** * Precompute the list of children symbols for all top-scope symbols. * I.e. For each x.y -> [x.y.z, x.y.w] */ void precomputeChildLists() { for (TypedVar var : compiler.getTopScope().getAllSymbols()) { String namespace = getNamespace(var.getName()); if (!namespace.equals("")) { if (!childListMap.containsKey(namespace)) childListMap.put(namespace, new ArrayList<TypedVar>()); childListMap.get(namespace).add(var); } } } /** * Finds all typedefs in the program and build a Type -> typedef name mapping. * The mapping is needed because when walking type definitions closure inlines the typedefs * values. */ void collectTypedefs() { for (TypedVar var : compiler.getTopScope().getAllSymbols()) { // In Closure, unlike TypeScript there is no pure type space. Thus even typedefs declare // symbols. The type of the symbol corresponding to the typedef is *not* the same as the type // declared by the typedef. JSType type = var.getType(); if (type == null || !isTypedef(type) || var.getName().startsWith("window.") || isPrivate(var.getJSDocInfo())) continue; JSType realType = compiler.getTypeRegistry().getType(var.getName()); if (realType != null && shouldEmitTypedefByName(realType)) { typedefs.put(realType, var.getName()); } } } /** * Whether the typedef should be emitted by name or by the type it is defining. * * Because, we do not access the original type signature, the replacement is done for * all references of the type (through the typedef or direct). Thus it is undesirable to always * emit by name. * For example: * @constructor A; * @typedef {A} B; * @const {A} var a; * If we emit the name, we would emit `var a: B;`, which is undesirable (consider A being string). * * For now, only emit by name typedefs that are unlikely to have more than one name referring to * them - record types, templatized types and function types. */ private boolean shouldEmitTypedefByName(JSType realType) { return realType.isRecordType() || realType.isTemplatizedType() || realType.isFunctionType(); } void generateDeclarations() { List<SourceFile> sourceFiles = new ArrayList<>(); for (String source : opts.arguments) { sourceFiles.add(SourceFile.fromFile(source, UTF_8)); } List<SourceFile> externFiles = new ArrayList<>(); for (String extern : opts.externs) { externFiles.add(SourceFile.fromFile(extern, UTF_8)); } String result = generateDeclarations(sourceFiles, externFiles, opts.depgraph); if ("-".equals(opts.output)) { System.out.println(result); } else { File output = new File(opts.output); try { Files.write(result, output, UTF_8); } catch (IOException e) { throw new IllegalArgumentException("Unable to write to file " + opts.output, e); } } } String generateDeclarations(List<SourceFile> sourceFiles, List<SourceFile> externs, Depgraph depgraph) throws AssertionError { compiler.compile(externs, sourceFiles, opts.getCompilerOptions()); precomputeChildLists(); collectTypedefs(); String dts = produceDts(depgraph); errorManager.doGenerateReport(); return dts; } private String getNamespace(String input) { int dotIdx = input.lastIndexOf('.'); if (dotIdx == -1) { return ""; } return input.substring(0, dotIdx); } String produceDts(Depgraph depgraph) { // Tree sets for consistent order. TreeSet<String> provides = new TreeSet<>(); Set<String> rewrittenProvides = new TreeSet<>(); Set<String> transitiveProvides = new TreeSet<>(); out = new StringWriter(); for (CompilerInput compilerInput : compiler.getInputsById().values()) { transitiveProvides.addAll(compilerInput.getProvides()); if (depgraph.isRoot(compilerInput.getSourceFile().getOriginalPath())) { provides.addAll(compilerInput.getProvides()); emitComment(String.format("Processing provides %s from input %s", compilerInput.getProvides(), compilerInput.getSourceFile().getOriginalPath())); } } Set<String> shadowedProvides = getShadowedProvides(provides); TypedScope topScope = compiler.getTopScope(); processReservedSymbols(provides, topScope); for (String provide : provides) { TypedVar symbol = topScope.getOwnSlot(provide); String emitName = provide; String rewritenProvide = "module$exports$" + provide.replace('.', '$'); TypedVar moduleTypeVar = topScope.getOwnSlot(rewritenProvide); if (moduleTypeVar != null) { // The provide came from a goog.module. symbol = moduleTypeVar; emitName = rewritenProvide; rewrittenProvides.add(rewritenProvide); } if (needsAlias(shadowedProvides, provide, symbol)) { emitName += Constants.SYMBOL_ALIAS_POSTFIX; } if (symbol == null) { // Sometimes goog.provide statements are used as pure markers for dependency management, or // the defined provides do not get a symbol because they don't have a proper type. emitNamespaceBegin(getNamespace(emitName)); emit("var"); emit(getUnqualifiedName(emitName)); emit(": any;"); emitBreak(); emitNamespaceEnd(); declareModule(provide, true, emitName); continue; } if (symbol.getType() == null) { emitComment("Skipping symbol " + symbol.getName() + " due to missing type information."); continue; } // ArrayLike is defined in lib.d.ts, so we skip any type alias that // would shadow it. // Note that clutz expands type aliases used in closure code, // thus this does not result in undefined types. // This case handles goog.provided typedefs. if (isTypedef(symbol.getType()) && isArrayLike(symbol)) { emitSkipTypeAlias(symbol); emitBreak(); continue; } String namespace = symbol.getName(); boolean isDefault = isDefaultExport(symbol); // These goog.provide's have only one symbol, so users expect to use default import if (isDefault) { namespace = getNamespace(symbol.getName()); } int valueSymbolsWalked = declareNamespace(namespace, symbol, emitName, isDefault, transitiveProvides, false); // skip emitting goog.require declarations for value empty namespaces, as calling typeof // does not work for them. if (valueSymbolsWalked > 0) { emitGoogRequireSupport(namespace, isDefault ? symbol.getName() : namespace, isDefault ? emitName : namespace); } declareModule(provide, isDefault, emitName); } // In order to typecheck in the presence of third-party externs, emit all extern symbols. processExternSymbols(); // For the purposes of determining which provides have been emitted // combine original provides and rewritten ones. provides.addAll(rewrittenProvides); processUnprovidedTypes(provides); checkState(indent == 0, "indent must be zero after printing, but is %s", indent); return out.toString(); } /** * Reserved words are problematic because they cannot be used as var declarations, but are valid * properties. For example: * var switch = 0; // parses badly in JS. * foo.switch = 0; // ok. * * This means that closure code is allowed to goog.provide('ng.components.switch'), which cannot * trivially translate in TS to: * namespace ng.components { * var switch : ...; * } * Instead, go one step higher and generate: * namespace ng { * var components : {switch: ..., }; * } * This turns a namespace into a property of its parent namespace. * Note: this violates the invariant that generated namespaces are 1-1 with getNamespace of * goog.provides. */ private void processReservedSymbols(TreeSet<String> provides, TypedScope topScope) { Set<String> collapsedNamespaces = new TreeSet<>(); for (String reservedProvide : provides) { if (reservedJsWords.contains(getUnqualifiedName(reservedProvide))) { String namespace = getNamespace(reservedProvide); if (collapsedNamespaces.contains(namespace)) continue; collapsedNamespaces.add(namespace); Set<String> properties = getSubNamespace(provides, namespace); emitNamespaceBegin(getNamespace(namespace)); emit("var"); emit(getUnqualifiedName(namespace)); emit(": {"); Iterator<String> bundledIt = properties.iterator(); while (bundledIt.hasNext()) { emit(getUnqualifiedName(bundledIt.next())); emit(":"); TypedVar var = topScope.getOwnSlot(reservedProvide); if (var != null) { TreeWalker walker = new TreeWalker(compiler.getTypeRegistry(), provides, false); walker.visitType(var.getType()); } else { emit("any"); } if (bundledIt.hasNext()) emit(","); } emit("};"); emitBreak(); emitNamespaceEnd(); for (String property : properties) { // Assume that all symbols that are siblings of the reserved word are default exports. declareModule(property, true, property, true); } } } // Remove the symbols that we have emitted above. Iterator<String> it = provides.iterator(); while(it.hasNext()) { if (collapsedNamespaces.contains(getNamespace(it.next()))) it.remove(); } } private Set<String> getSubNamespace(TreeSet<String> symbols, String namespace) { return symbols.subSet(namespace + ".", namespace + ".\uFFFF"); } private Set<String> getShadowedProvides(TreeSet<String> provides) { Set<String> shadowedProvides = new TreeSet<>(); for (String provide : provides) { if (!getSubNamespace(provides, provide).isEmpty()) { shadowedProvides.add(provide); } } return shadowedProvides; } private boolean isArrayLike(TypedVar symbol) { return symbol.getName().endsWith(".ArrayLike"); } /** * Closure does not require all types to be explicitly provided, if they are only used in type * positions. However, our emit phases only emits goog.provided symbols and namespaces, so this * extra pass is required, in order to have valid output. */ private void processUnprovidedTypes(Set<String> provides) { int maxTypeUsedDepth = 5; Set<String> typesEmitted = new LinkedHashSet<>(); while (maxTypeUsedDepth > 0) { int typesUsedCount = typesUsed.size(); // AFAICT, there is no api for going from type to symbol, so iterate all symbols first. for (TypedVar symbol : compiler.getTopScope().getAllSymbols()) { String name = symbol.getName(); // skip unused symbols, symbols already emitted or symbols whose namespace is emitted. if (!typesUsed.contains(name) || typesEmitted.contains(name) || typesEmitted.contains(getNamespace(name))) { continue; } // skip provided symbols (as default or in an namespace). if (provides.contains(name) || provides.contains(getNamespace(name))) continue; // skip extern symbols (they have a separate pass). CompilerInput symbolInput = this.compiler.getInput(new InputId(symbol.getInputName())); if (symbolInput != null && symbolInput.isExtern()) continue; declareNamespace(getNamespace(name), symbol, name, /* isDefault */ true, Collections.<String>emptySet(), /* isExtern */ false); typesEmitted.add(name); } // if no new types seen, safely break out. if (typesUsed.size() == typesUsedCount) break; maxTypeUsedDepth } } private void processExternSymbols() { Set<String> visitedClassLikes = new TreeSet<>(); List<TypedVar> externSymbols = new ArrayList<>(); TreeSet<String> externSymbolNames = new TreeSet<>(); final TreeSet<String> enumElementSymbols = new TreeSet<>(); for (TypedVar symbol : compiler.getTopScope().getAllSymbols()) { CompilerInput symbolInput = compiler.getInput(new InputId(symbol.getInputName())); if (symbolInput == null || !symbolInput.isExtern() || symbol.getType() == null) { continue; } if (!opts.emitPlatformExterns && isPlatformExtern(symbolInput.getName(), symbol.getName())) { continue; } JSType type = symbol.getType(); // Closure treats all prototypes as separate symbols, but we handle them in conjunction with // parent symbol. if (symbol.getName().contains(".prototype")) continue; // Sub-parts of namespaces in externs can appear as unknown if they miss a @const. if (type.isUnknownType()) continue; if (type.isEnumType()) { EnumType eType = (EnumType) type; for (String element : eType.getElements()) { enumElementSymbols.add(symbol.getName() + "." + element); } } externSymbols.add(symbol); externSymbolNames.add(symbol.getName()); } Iterator<TypedVar> it = externSymbols.iterator(); while (it.hasNext()) { // Some extern symbols appear twice, once unprefixed, and once prefixed with window. // Skip the second one, if both exist. TypedVar symbol = it.next(); if (symbol.getName().startsWith("window.") && externSymbolNames.contains(symbol.getName().substring(7))) { it.remove(); externSymbolNames.remove(symbol.getName()); } } // Enum values like Enum.A will appear as stand-alone symbols, but we do not need to emit them. externSymbolNames.removeAll(enumElementSymbols); it = externSymbols.iterator(); while (it.hasNext()) { if (enumElementSymbols.contains(it.next().getName())) { it.remove(); } } sortSymbols(externSymbols); Set<String> shadowedSymbols = getShadowedProvides(externSymbolNames); for (TypedVar symbol : externSymbols) { String parentPath = getNamespace(symbol.getName()); boolean isDefault = isDefaultExport(symbol); String emitName = symbol.getName(); if (needsAlias(shadowedSymbols, symbol.getName(), symbol)) { emitName += Constants.SYMBOL_ALIAS_POSTFIX; } // There is nothing to emit for a namespace, because all its symbols will be visited later, // thus implicitly defining the namespace. if (isLikelyNamespace(symbol.getJSDocInfo())) continue; // Do not emit static fields as symbols, since they were already emitted in the class // definition. if (!isDefiningType(symbol.getType()) && visitedClassLikes.contains(parentPath)) continue; declareNamespace(isDefault ? parentPath : symbol.getName(), symbol, emitName, isDefault, shadowedSymbols, true); if (isDefault && isClassLike(symbol.getType())) visitedClassLikes.add(symbol.getName()); // we do not declare modules or goog.require support, because externs types should not be // visible from TS code. } } private static final Ordering<TypedVar> BY_VAR_NAME = Ordering.natural().onResultOf(new Function<TypedVar, Comparable<String>>() { @Nullable @Override public Comparable<String> apply(@Nullable TypedVar input) { if (input == null) return null; return input.getName(); } }); private void sortSymbols(List<TypedVar> symbols) { Collections.sort(symbols, BY_VAR_NAME); } private boolean needsAlias(Set<String> shadowedSymbols, String provide, TypedVar symbol) { if (!shadowedSymbols.contains(provide)) return false; // Emit var foo : any for provided but not declared symbols. if (symbol == null) return true; JSType type = symbol.getType(); // Emit var foo : PrivateType for private symbols. if (isPrivate(type.getJSDocInfo()) && !isConstructor(type.getJSDocInfo())) return true; // Only var declarations have collisions, while class, interface, and functions can coexist with // namespaces. if (type != null && (type.isInterface() || type.isConstructor() || type.isFunctionType())) { return false; } return isDefaultExport(symbol); } private boolean isDefaultExport(TypedVar symbol) { if (symbol.getType() == null) return true; ObjectType otype = symbol.getType().toMaybeObjectType(); if (otype != null && otype.getOwnPropertyNames().size() == 0) return true; return !symbol.getType().isObject() || symbol.getType().isInterface() || symbol.getType().isInstanceType() || symbol.getType().isEnumType() || symbol.getType().isFunctionType() || isTypedef(symbol.getType()); } /** For platform externs we skip emitting, to avoid collisions with lib.d.ts. */ private boolean isPlatformExtern(String filePath, String symbolName) { // Some symbols are not yet provided by lib.d.ts, so we have to emit them. if (platformSymbolsMissingInTypeScript.contains(symbolName)) return false; // This matches our test setup. if (filePath.startsWith("externs.zip//")) return true; String fileName = new File(filePath).getName(); // This loosly matches the filenames from return platformExternsFilenames.contains(fileName) || fileName.startsWith("es") || fileName.startsWith("gecko_") || fileName.startsWith("w3c_") || fileName.startsWith("ie_") || fileName.startsWith("webkit_"); } /** * @return the number of value symbols emitted. If this number is greater than zero, the namespace * can be used in a value position, for example `typeof foo`. */ private int declareNamespace(String namespace, TypedVar symbol, String emitName, boolean isDefault, Set<String> provides, boolean isExtern) { if (!isValidJSProperty(getUnqualifiedName(symbol))) { emitComment("skipping property " + symbol.getName() + " because it is not a valid symbol."); return 0; } emitNamespaceBegin(namespace); TreeWalker treeWalker = new TreeWalker(compiler.getTypeRegistry(), provides, isExtern); if (isDefault) { if (isPrivate(symbol.getJSDocInfo()) && !isConstructor(symbol.getJSDocInfo())) { treeWalker.emitPrivateValue(emitName); } else { treeWalker.walk(symbol, emitName); } } else { // JSCompiler treats "foo.x" as one variable name, so collect all provides that start with // $provide + "." but are not sub-properties. Set<String> desiredSymbols = new TreeSet<>(); List<TypedVar> allSymbols = Lists.newArrayList(compiler.getTopScope().getAllSymbols()); sortSymbols(allSymbols); ObjectType objType = (ObjectType) symbol.getType(); // Can be null if the symbol is provided, but not defined. Set<String> propertyNames = objType != null ? objType.getPropertyNames() : Collections.<String>emptySet(); for (String property : propertyNames) { // When parsing externs namespaces are explicitly declared with a var of Object type // Do not emit the var declaration, as it will conflict with the namespace. if (!(isEmittableProperty(objType, property) && isValidJSProperty(property) || (isExtern && isLikelyNamespace(objType.getOwnPropertyJSDocInfo(property))))) { desiredSymbols.add(symbol.getName() + "." + property); } } // Any provides have their own namespace and should not be emitted in this namespace. for (String provide : provides) { String toRemove = provide; while (!toRemove.isEmpty()) { desiredSymbols.remove(toRemove); // Also remove their implicit parent namespaces toRemove = toRemove.substring(0, Math.max(0, toRemove.lastIndexOf('.'))); } } for (TypedVar propertySymbol : allSymbols) { String propertyName = propertySymbol.getName(); if (desiredSymbols.contains(propertyName) && propertySymbol.getType() != null && !propertySymbol.getType().isFunctionPrototypeType() && !isPrototypeMethod(propertySymbol)) { if (!isValidJSProperty(getUnqualifiedName(propertySymbol))) { emitComment("skipping property " + propertyName + " because it is not a valid symbol."); continue; } // For safety we need to special case goog.require to return the empty interface by // default // For existing namespaces we emit a goog.require string override that has the proper // type. // See emitGoogRequireSupport method. if (propertyName.equals("goog.require")) { emit("function require (name : string ) : " + Constants.INTERNAL_NAMESPACE + ".ClosureSymbolNotGoogProvided;"); emitBreak(); continue; } try { treeWalker.walk(propertySymbol, propertyName); } catch (RuntimeException e) { // Do not throw DeclarationGeneratorException - this is an unexpected runtime error. throw new RuntimeException("Failed to emit for " + propertySymbol, e); } } } } emitNamespaceEnd(); // extra walk required for inner classes and inner enums. They are allowed in closure, // but not in TS, so we have to generate a namespace-class pair in TS. // In the case of the externs, however we *do* go through all symbols so this pass is not // needed. // In the case of aliased classes, we cannot emit inner classes, due to a var-namespace clash. ObjectType otype = symbol.getType().toMaybeObjectType(); if (isDefault && !isExtern && otype != null && !isAliasedClassOrInterface(symbol, otype)) { treeWalker.walkInnerSymbols(otype, symbol.getName()); } return treeWalker.valueSymbolsWalked; } private boolean isValidJSProperty(String name) { // Ignoring Unicode symbols for now. return Pattern.matches("^[$a-zA-Z_][0-9a-zA-Z_$]*$", name); } /** * Returns whether the author tried to express the concept of a namespace in Closure. * TS has a first-class keyword for it, but in Closure we need to infer it from the JSDoc. * Roughly, a namespace is a static object used for hierarchically organizing values. * TODO(rado): this might still have some false positives. A more robust check would also * verify that there are child properties (an empty namespace is not useful). */ private boolean isLikelyNamespace(JSDocInfo doc) { if (doc == null) return false; // Authors should prefer @const to express a namespace in externs, and just goog.provide it // in non-extern code. However, there are still usages of @type {Object}. JSTypeExpression type = doc.getType(); if (type != null && type.getRoot().isString() && type.getRoot().getString().equals("Object")) { return true; } return doc.hasConstAnnotation() && !doc.hasType(); } /** * Returns true if {@code propType} is creating a new type in the TypeScript sense - i.e. it's a * constructor function (class or interface), enum, or typedef. */ private boolean isDefiningType(JSType propType) { return isClassLike(propType) || propType.isEnumType() || propType.isInterface() || isTypedef(propType); } /** * Returns true for types that are class like, i.e. that define a constructor or interface, but * excludes typedefs and the built-in constructor functions such as {@code Function}. */ private boolean isClassLike(JSType propType) { // Confusingly, the typedef type returns true on isConstructor checks, so we need to filter // the NoType through this utility method. return !isTypedef(propType) && (propType.isConstructor() || propType.isInterface()) // "Function" is a constructor, but does not define a new type for our purposes. && !propType.toMaybeObjectType().isNativeObjectType() && !propType.isFunctionPrototypeType(); } // This indirection exists because the name in the Closure APIs is confusing. // TODO(rado): figure out if NoType can be created through other means and more filtering is // needed here. private boolean isTypedef(JSType type) { return type.isNoType(); } private void emitGoogRequireSupport(String namespace, String nameToBeRequired, String emitName) { // goog namespace doesn't need to be goog.required. if (namespace.equals("goog")) return; emitNamespaceBegin("goog"); // TS supports overloading the require declaration with a fixed string argument. emit("function require(name: '" + nameToBeRequired + "'): typeof " + Constants.INTERNAL_NAMESPACE + "." + emitName + ";"); emitBreak(); emitNamespaceEnd(); } private void emitNamespaceBegin(String namespace) { emitNoSpace("declare namespace "); emitNoSpace(Constants.INTERNAL_NAMESPACE); if (!namespace.isEmpty()) { emitNoSpace("." + namespace); } emitNoSpace(" {"); indent(); emitBreak(); } private void emitNamespaceEnd() { unindent(); emit("}"); emitBreak(); } private boolean isPrototypeMethod(TypedVar other) { if (other.getType() != null && other.getType().isOrdinaryFunction()) { JSType typeOfThis = ((FunctionType) other.getType()).getTypeOfThis(); if (typeOfThis != null && !typeOfThis.isUnknownType()) { return true; } } return false; } private boolean isEmittableProperty(ObjectType obj, String propName) { JSDocInfo info = obj.getOwnPropertyJSDocInfo(propName); // Skip emitting private properties, but do emit constructors because they introduce a // type that can be used in type contexts. return isPrivate(info) && !isConstructor(info); } private boolean isTypeCheckSuppressedProperty(ObjectType obj, String propName) { JSDocInfo info = obj.getOwnPropertyJSDocInfo(propName); return info != null && info.getSuppressions().contains("checkTypes"); } private boolean isPrivate(JSType type) { // for a typedef. Assume non-private as it is more common. // Closure creates a NamedType when the typedef is used in an union, eg: T | null. // Dereference the named type before checking if it is a typedef. NamedType nType = type.toMaybeNamedType(); if (typedefs.containsKey(type) || nType != null && typedefs.containsKey(nType.getReferencedType())) { return false; } // For unknown reasons, enum types do not keep their defining jsdoc info. if (type.isEnumType() || type.isEnumElementType()) { return isPrivate(type.getDisplayName()); } else { return isPrivate(type.getJSDocInfo()); } } private boolean isPrivate(String name) { TypedVar var = compiler.getTopScope().getOwnSlot(name); if (var == null) return false; return isPrivate(var.getJSDocInfo()); } private boolean isPrivate(@Nullable JSDocInfo docInfo) { return docInfo != null && docInfo.getVisibility() == Visibility.PRIVATE; } private boolean isConstructor(@Nullable JSDocInfo docInfo) { return docInfo != null && docInfo.isConstructor(); } private void declareModule(String name, boolean isDefault, String emitName) { declareModule(name, isDefault, emitName, false); } private void declareModule(String name, boolean isDefault, String emitName, boolean inParentNamespace) { emitNoSpace("declare module '"); emitNoSpace("goog:" + name); emitNoSpace("' {"); indent(); emitBreak(); emit("import alias = "); emitNoSpace(Constants.INTERNAL_NAMESPACE); emitNoSpace("."); emitNoSpace(inParentNamespace ? getNamespace(emitName) : emitName); emitNoSpace(";"); emitBreak(); if (isDefault) { emitNoSpace("export default alias"); if (inParentNamespace) emitNoSpace("." + getUnqualifiedName(name)); emitNoSpace(";"); } else { emitNoSpace("export = alias;"); } emitBreak(); unindent(); emit("}"); emitBreak(); } static List<SourceFile> getDefaultExterns(Options opts) { try { return AbstractCommandLineRunner.getBuiltinExterns( opts.getCompilerOptions().getEnvironment()); } catch (IOException e) { throw new RuntimeException("Could not locate builtin externs", e); } } private int indent = 0; private boolean startOfLine = true; private void indent() { indent++; } private void unindent() { indent checkState(indent >= 0, "indentation level below zero"); } private void emitNoSpace(String str) { maybeEmitIndent(); out.write(str); } private void emit(String str) { Preconditions.checkNotNull(str); if (!maybeEmitIndent()) { out.write(" "); } out.write(str); } private boolean maybeEmitIndent() { if (!startOfLine) { return false; } for (int i = 0; i < indent; i++) { out.write(" "); } startOfLine = false; return true; } private void emitBreak() { out.write("\n"); startOfLine = true; } // We use a syntax for comments that we can strip in unit tests private void emitComment(String s) { emit(" emit(s); emitBreak(); } private ObjectType getSuperType(FunctionType type) { ObjectType proto = type.getPrototype(); if (proto == null) return null; ObjectType implicitProto = proto.getImplicitPrototype(); if (implicitProto == null) return null; return "Object".equals(implicitProto.getDisplayName()) ? null : implicitProto; } private String getUnqualifiedName(TypedVar symbol) { return getUnqualifiedName(symbol.getName()); } private String getUnqualifiedName(String name) { return lastDottedPart(name); } private String lastDottedPart(String input) { int dotIdx = input.lastIndexOf('.'); if (dotIdx == -1) { return input; } return input.substring(dotIdx + 1, input.length()); } private class TreeWalker { private final JSTypeRegistry typeRegistry; private final Set<String> provides; /** Whether the symbol we are walking was defined in an extern file */ private final boolean isExtern; private int valueSymbolsWalked = 0; /** * The void type in closure contains only the undefined value. */ private final Predicate<JSType> isVoidType = new Predicate<JSType>() { @Override public boolean apply(JSType type) { return type.isVoidType(); } }; private TreeWalker(JSTypeRegistry typeRegistry, Set<String> provides, boolean isExtern) { this.typeRegistry = typeRegistry; this.provides = provides; this.isExtern = isExtern; } private String getAbsoluteName(ObjectType objectType) { String name = objectType.getDisplayName(); // Names that do not have a namespace '.' are either platform names in the top level // namespace like `Object` or `Element`, or they are unqualified `goog.provide`s, e.g. // `goog.provide('Toplevel')`. In both cases they will be found with the naked name. // However a goog.provide'd name can collide with a re-declared top-level symbol, e.g. if some // code goog.provide's `Element`. // TODO(martinprobst): Consider aliasing all global symbols into the clutz namespace. if (name.indexOf('.') == -1) return name; return Constants.INTERNAL_NAMESPACE + "." + name; } private void walk(TypedVar symbol, String emitName) { JSType type = symbol.getType(); if (!type.isInterface() && !isTypedef(type)) valueSymbolsWalked++; if (type.isFunctionType() && !isNewableFunctionType((FunctionType) type)) { FunctionType ftype = (FunctionType) type; if (isOrdinaryFunction(ftype)) { maybeEmitJsDoc(symbol.getJSDocInfo(), /* ignoreParams */ false); visitFunctionExpression(getUnqualifiedName(symbol), ftype); return; } maybeEmitJsDoc(symbol.getJSDocInfo(), /* ignoreParams */ true); // The class/interface symbol might be an alias for another symbol. // Since closure inlines all aliases before this step, check against // the type name. if (!isAliasedClassOrInterface(symbol, ftype)) { visitClassOrInterface(getUnqualifiedName(symbol), ftype); } else { visitClassOrInterfaceAlias(getUnqualifiedName(symbol), ftype); } } else { maybeEmitJsDoc(symbol.getJSDocInfo(), /* ignoreParams */ false); if (type.isEnumType()) { visitEnumType(emitName, (EnumType) type); return; } if (isTypedef(type)) { // ArrayLike is defined in lib.d.ts, so we skip any type alias that // would shadow it. // Note that clutz expands type aliases used in closure code, // thus this does not result in undefined types. // This case handles not goog.provided typedefs. if (isArrayLike(symbol)) { emitSkipTypeAlias(symbol); emitBreak(); return; } // The aliased type is present in the registry under the symbol name. JSType registryType = typeRegistry.getType(symbol.getName()); if (registryType != null) { visitTypeAlias(registryType, symbol); return; } else { emitComment("Intended to visit type alias '" + symbol.getName() + " but type not found in Closure type registry."); } } visitVarDeclaration(getUnqualifiedName(emitName), type); } } /** * Used to differentiate a function with a constructor function type, from ordinary ones. * <code> @type {function(new:X)} foo.x;</code> * isNominalConstructor cannot be used because it returns true for all * classes/interfaces that have = function() {} (even if they are structural interfaces!). * That means valid interfaces are considered non-nominal, like * var I; (in externs) // or * ns.I = goog.nullFunction(); */ private boolean isNewableFunctionType(FunctionType type) { // Not sure why, but null display name is a good differentiator of newable functions. return type.isConstructor() && type.getDisplayName() == null; } private void visitClassOrInterfaceAlias(String unqualifiedName, FunctionType ftype) { String typeName = Constants.INTERNAL_NAMESPACE + "." + ftype.getDisplayName(); emit("type"); emit(unqualifiedName); visitTemplateTypes(ftype); emit("="); emit(typeName); visitTemplateTypes(ftype); emit(";"); emitBreak(); if (!ftype.isInterface()) { // TS type aliases are only useful in type positions. // To emulate closure alias semantics, introduce also an aliased constructor emit("var " + unqualifiedName); emit(":"); emit("typeof"); emit(typeName); emit(";"); emitBreak(); } typesUsed.add(ftype.getDisplayName()); } private void maybeEmitJsDoc(JSDocInfo docs, boolean ignoreParams) { if (docs == null) return; String desc = docs.getBlockDescription(); if (desc == null) return; emit("/**"); emitBreak(); if (desc != null) { for (String line : Splitter.on('\n').split(desc)) { emit(" *"); if (!line.isEmpty()) emit(line); emitBreak(); } } if (!ignoreParams) { for (String name : docs.getParameterNames()) { if (docs.getDescriptionForParameter(name) == null) continue; emit(" * @param"); emit(name); emit(docs.getDescriptionForParameter(name)); emitBreak(); } } emit(" */"); emitBreak(); } private void visitClassOrInterface(String name, FunctionType ftype) { // TypeScript classes (like ES6 classes) have prototypal inheritance on the static side, // which means that if A extends B, A.foo and B.foo cannot be of incompatible types. // Closure (ES5) classes have no such restriction. // To avoid collisions on the static side, emit all statics in the original class name A, // and emit instance fields in another class A_Instance. As such: // class A extends A_Instance { <static fields and methods> } // class B extends B_Instance { <static fields and methods> } // class A_Instance extends B_Instance { <instance fields and methods> } // class B_Instance { <instance fields and methods> } // Emit original name class before Instance in order to match the already emitted JSDoc. final boolean emitInstance = !ftype.isInterface(); if (emitInstance) { emit("class"); emit(name); visitTemplateTypes(ftype); emit("extends"); emit(name + INSTANCE_CLASS_SUFFIX); visitTemplateTypes(ftype); emit("{"); indent(); emitBreak(); // we pass an empty set because static function can never refer to a TemplateType defined // on the class visitProperties(ftype, true); unindent(); emit("}"); emitBreak(); } if (ftype.isConstructor()) { // "proper" class constructor emit("class"); } else if (ftype.isInterface()) { emit("interface"); } else { checkState(false, "Unexpected function type " + ftype); } emit(emitInstance ? name + INSTANCE_CLASS_SUFFIX : name); visitTemplateTypes(ftype); // Interface extends another interface if (ftype.getExtendedInterfacesCount() > 0) { emit("extends"); Iterator<ObjectType> it = ftype.getExtendedInterfaces().iterator(); emitCommaSeparatedInterfaces(it); } // Class extends another class ObjectType superType = getSuperType(ftype); if (superType != null) { emit("extends"); boolean emitInstanceForObject = emitInstance && (opts.emitPlatformExterns || !isDefinedInPlatformExterns(superType)); Visitor<Void> visitor = new ExtendsImplementsTypeVisitor(emitInstanceForObject); superType.visit(visitor); } Iterator<ObjectType> it = ftype.getOwnImplementedInterfaces().iterator(); if (it.hasNext()) { emit("implements"); emitCommaSeparatedInterfaces(it); } visitObjectType(ftype, ftype.getPrototype(), getTemplateTypeNames(ftype)); } private void emitCommaSeparatedInterfaces(Iterator<ObjectType> it) { while (it.hasNext()) { ObjectType type = it.next(); if (isPrivate(type.getJSDocInfo()) && !isConstructor(type.getJSDocInfo())) { // TypeScript does not allow public APIs that expose non-exported/private types. emit(Constants.INTERNAL_NAMESPACE + ".PrivateInterface"); } else { ExtendsImplementsTypeVisitor visitor = new ExtendsImplementsTypeVisitor(false); type.visit(visitor); } if (it.hasNext()) { emit(","); } } } private void visitVarDeclaration(String name, JSType type) { emit("var"); emit(name); visitTypeDeclaration(type, false, false); emit(";"); emitBreak(); } private void visitTemplateTypes(ObjectType type) { visitTemplateTypes(type, Collections.<String>emptySet()); } private void visitTemplateTypes(ObjectType type, Set<String> alreadyEmittedTemplateType) { if (type.hasAnyTemplateTypes() && !type.getTemplateTypeMap().isEmpty()) { List<String> realTemplateType = new ArrayList<>(); for (TemplateType templateType : type.getTemplateTypeMap().getTemplateKeys()) { String displayName = templateType.getDisplayName(); // Some template variables can be already defined at the class definition. // Closure and TypeScript disagree in that case, in closure redeclaring a class template // variable at a method does nothing, but in Typescript it introduces a new variable. // To perserve the sementics from closure we skip emitting redeclared variables. if (alreadyEmittedTemplateType.contains(displayName)) { continue; } if (displayName.contains("IObject displayName = normalizeIObjectTemplateName(type, displayName); } if (displayName != null) { realTemplateType.add(displayName); } } if (!realTemplateType.isEmpty()) { emit("<"); emit(Joiner.on(" , ").join(realTemplateType)); emit(">"); } } } private String normalizeIObjectTemplateName(ObjectType type, String displayName) { // IObject itself needs too keep the template names, as it is a trully parametric type. if (type.getDisplayName().equals("IObject")) { return displayName.substring(displayName.indexOf(' } // For other types, we use index signatures in TS to express the same concept, so skip // emitting. return null; } private void visitTypeAlias(JSType registryType, TypedVar symbol) { visitTypeAlias(registryType, getUnqualifiedName(symbol)); } private void visitTypeAlias(JSType registryType, String unqualifiedName) { emit("type"); emit(unqualifiedName); emit("="); visitType(registryType, true, false); emit(";"); emitBreak(); } private void visitEnumType(String symbolName, EnumType type) { // Enums are top level vars, but also declare a corresponding type: // <pre> // /** @enum {ValueType} */ var MyEnum = {A: ..., B: ...}; // type MyEnum = EnumValueType; // var MyEnum: {A: MyEnum, B: MyEnum, ...}; // </pre> // TODO(martinprobst): Special case number enums to map to plain TS enums? String unqualifiedName = getUnqualifiedName(symbolName); // TS `type` declarations accept only unqualified names. visitTypeAlias(type.getElementsType().getPrimitiveType(), unqualifiedName); emit("var"); emit(unqualifiedName); emit(": {"); emitBreak(); indent(); for (String elem : sorted(type.getElements())) { emit(elem); emit(":"); // No need to use type.getMembersType(), this must match the type alias we just declared. emit(unqualifiedName); emit(","); emitBreak(); } unindent(); emit("}"); emitNoSpace(";"); emitBreak(); } private void visitTypeDeclaration(JSType type, boolean isVarArgs, boolean isOptionalPosition) { if (type != null) { emit(":"); // From https://github.com/Microsoft/TypeScript/blob/master/doc/spec.md#a-grammar // ArrayType: // PrimaryType [no LineTerminator here] [ ] if (isVarArgs) { visitTypeAsPrimary(type); } else { visitType(type, false, isOptionalPosition); } if (isVarArgs) emit("[]"); } } private void visitTypeAsPrimary(JSType type) { // These types will produce a non-primary grammar production if (!isLiteralFunction(type) && (type.isConstructor() || type.isFunctionType() || type.isUnionType())) { emit("("); visitType(type); emit(")"); } else { visitType(type); } } private void visitType(JSType typeToVisit) { visitType(typeToVisit, false, false); } private void visitType(JSType typeToVisit, boolean skipDefCheck, final boolean inOptionalPosition) { // Known typedefs will be emitted symbolically instead of expanded. if (!skipDefCheck && typedefs.containsKey(typeToVisit)) { String typedefName = typedefs.get(typeToVisit); emit(Constants.INTERNAL_NAMESPACE + "." + typedefName); typesUsed.add(typedefName); return; } // See also JsdocToEs6TypedConverter in the Closure code base. This code is implementing the // same algorithm starting from JSType nodes (as opposed to JSDocInfo), and directly // generating textual output. Otherwise both algorithms should produce the same output. if (isPrivate(typeToVisit) && !isConstructor(typeToVisit.getJSDocInfo())) { // TypeScript does not allow public APIs that expose non-exported/private types. Just emit // an empty object literal type for those, i.e. something that cannot be used for anything, // except being passed around. emit(Constants.INTERNAL_NAMESPACE + ".PrivateType"); return; } Visitor<Void> visitor = new Visitor<Void>() { @Override public Void caseBooleanType() { emit("boolean"); return null; } @Override public Void caseNumberType() { emit("number"); return null; } @Override public Void caseStringType() { emit("string"); return null; } @Override public Void caseObjectType(ObjectType type) { return emitObjectType(type, false, false); } @Override public Void caseUnionType(UnionType type) { visitUnionType(type, inOptionalPosition); return null; } @Override public Void caseNamedType(NamedType type) { visitType(type.getReferencedType()); return null; } @Override public Void caseTemplatizedType(TemplatizedType type) { return emitTemplatizedType(type, false, false); } @Override public Void caseTemplateType(TemplateType templateType) { emit(templateType.getReferenceName()); return null; } @Override public Void caseNoType(NoType type) { emit("any"); return null; } @Override public Void caseAllType() { emit("any"); return null; } @Override public Void caseNoObjectType() { emit("any"); return null; } @Override public Void caseUnknownType() { emit("any"); return null; } @Override public Void caseNullType() { emit("null"); return null; } @Override public Void caseVoidType() { // In Closure "void" and "undefined" are type synonyms. Both types are // inhabited only by the value undefined. // In TS emitting "undefined" is more ideomatic in a general type position. // For function return types clutz emits "void" in visitFunctionDeclaration. // see: https://github.com/google/closure-compiler/blob/caec92d5f62e745d20a0b4b8edb757d43b06baa0/src/com/google/javascript/rhino/jstype/JSTypeRegistry.java#L1011 emit("undefined"); return null; } @Override public Void caseEnumElementType(EnumElementType type) { emit(getAbsoluteName(type)); typesUsed.add(type.getDisplayName()); return null; } @Override public Void caseFunctionType(FunctionType type) { if (isLiteralFunction(type)) { emit("Function"); return null; } if (type.isConstructor() && !"Function".equals(type.getDisplayName())) { visitConstructorFunctionDeclaration(type); return null; } visitFunctionParameters(type); JSType returnType = type.getReturnType(); if (returnType != null) { emit("=>"); visitType(returnType); } return null; } @Override public Void caseProxyObjectType(ProxyObjectType type) { type.visitReferenceType(this); return null; } }; try { typeToVisit.visit(visitor); } catch (Exception e) { throw new RuntimeException("Failed to emit type " + typeToVisit, e); } } /** Whether the type was written as the literal 'Function' type */ private boolean isLiteralFunction(JSType type) { return type == typeRegistry.getNativeType(JSTypeNative.FUNCTION_INSTANCE_TYPE); } private Void emitTemplatizedType(TemplatizedType type, boolean extendingInstanceClass, boolean inImplementsExtendsPosition) { ObjectType referencedType = type.getReferencedType(); String templateTypeName = extendingInstanceClass ? getAbsoluteName(type) + INSTANCE_CLASS_SUFFIX : getAbsoluteName(type); if (typeRegistry.getNativeType(ARRAY_TYPE).equals(referencedType) && type.getTemplateTypes().size() == 1) { // As per TS type grammar, array types require primary types. // https://github.com/Microsoft/TypeScript/blob/master/doc/spec.md#a-grammar if (inImplementsExtendsPosition) { emit("Array<"); } visitTypeAsPrimary(type.getTemplateTypes().get(0)); emit(inImplementsExtendsPosition ? ">" : "[]"); return null; } if (!opts.emitPlatformExterns) { switch (type.getDisplayName()) { // Arguments<?> and NodeList<?> in es3 externs are correspondingly // IArguments and NodeList interfaces (not-parametrized) in lib.d.ts. case "Arguments": emit("IArguments"); return null; case "NodeList": emit("NodeList"); return null; case "MessageEvent": emit("MessageEvent"); return null; case "IThenable": templateTypeName = "PromiseLike"; break; case "IArrayLike": templateTypeName = "ArrayLike"; break; default: break; } } if (type.getTemplateTypes().isEmpty()) { // In Closure, subtypes of `TemplatizedType`s that do not take type arguments are still // represented by templatized types. emit(templateTypeName); typesUsed.add(type.getDisplayName()); return null; } Iterator<JSType> it = type.getTemplateTypes().iterator(); if (typeRegistry.getNativeType(OBJECT_TYPE).equals(referencedType)) { emit("{"); emitIndexSignature(it.next(), it.next(), false); emit("}"); return null; } emit(templateTypeName); typesUsed.add(type.getDisplayName()); emit("<"); while (it.hasNext()) { visitType(it.next()); if (it.hasNext()) { emit(","); } } emit(">"); return null; } private void emitIndexSignature(JSType keyType, JSType returnType, boolean emitBreak) { emit("["); // TS allows only number or string as index type of an object // https://github.com/Microsoft/TypeScript/blob/master/doc/spec.md#3.9.4 if (keyType.isNumberValueType()) { emit("key: number"); } else { if (!keyType.isStringValueType()) { emit("/* warning: coerced from " + keyType + " */"); } emit("key: string"); } emit("]:"); visitType(returnType); if (emitBreak) { emit(";"); emitBreak(); } } private void visitRecordType(RecordType type) { emit("{"); Iterator<String> it = getSortedPropertyNamesToEmit(type).iterator(); while (it.hasNext()) { String propName = it.next(); emit(propName); UnionType unionType = type.getPropertyType(propName).toMaybeUnionType(); if (unionType != null && any(unionType.getAlternates(), isVoidType)) { emit("?"); visitTypeDeclaration(type.getPropertyType(propName), false, true); } else { visitTypeDeclaration(type.getPropertyType(propName), false, false); } if (it.hasNext()) { emit(","); } } emit("}"); } private Set<String> getSortedPropertyNamesToEmit(final ObjectType type) { return sorted(Sets.filter(type.getOwnPropertyNames(), new Predicate<String>() { @Override public boolean apply(String propName) { return !isEmittableProperty(type, propName) && !isTypeCheckSuppressedProperty(type, propName); } })); } private Set<String> sorted(Set<String> elements) { return new TreeSet<>(elements); } private void visitUnionType(UnionType ut, boolean inOptionalPosition) { Collection<JSType> alts = ut.getAlternates(); // When visiting an optional function argument or optional field (`foo?` syntax), // TypeScript will augment the provided type with an union of undefined, i.e. `foo?: T` will // means defacto `foo` has type `T | undefined` in the body. // Skip explicitly emitting the undefined union in such cases. if (inOptionalPosition) { alts = Collections2.filter(alts, new Predicate<JSType>() { @Override public boolean apply(JSType input) { return !input.isVoidType(); } }); } if (alts.size() == 0) { // If the only type was "undefined" and it got filtered, emit it explicitly. emit("undefined"); return; } if (alts.size() == 1) { visitType(alts.iterator().next()); return; } Iterator<JSType> it = alts.iterator(); while (it.hasNext()) { // See https://github.com/Microsoft/TypeScript/blob/master/doc/spec.md#a-grammar // UnionType: // UnionOrIntersectionOrPrimaryType | IntersectionOrPrimaryType visitTypeAsPrimary(it.next()); if (it.hasNext()) { emit("|"); } } } private void visitObjectType(FunctionType type, ObjectType prototype, Set<String> classTemplateTypeNames) { emit("{"); indent(); emitBreak(); // Prevent accidental structural typing - emit every class with a private field. if (type.isNominalConstructor() && !type.isInterface() // But only for non-extending classes (TypeScript doesn't like overriding private fields) && getSuperType(type) == null) { emit("private noStructuralTyping_: any;"); emitBreak(); } // Constructors. if (type.isConstructor() && (type).getParameters().iterator().hasNext() && !isPrivate( type.getJSDocInfo())) { maybeEmitJsDoc(type.getJSDocInfo(), /* ignoreParams */ false); // TODO(radokirov): mark constuctor as private when source is annotated with // @private for ts v2.0 and greater emit("constructor"); visitFunctionParameters(type, false, classTemplateTypeNames); emit(";"); emitBreak(); } Set<String> superClassFields = getSuperClassFields(type); // Fields. JSType instanceType = type.getTypeOfThis(); checkArgument(instanceType.isObject(), "expected an ObjectType for this, but got " + instanceType + " which is a " + instanceType.getClass().getSimpleName()); visitProperties((ObjectType) instanceType, false, Collections.<String>emptySet(), Collections.<String>emptySet(), superClassFields); // Bracket-style property access for dictionnary... if (type.isDict()) { emitIndexSignature( compiler.getTypeRegistry().getNativeType(STRING_TYPE), compiler.getTypeRegistry().getNativeType(ALL_TYPE), true); } // ... and type that extends IObject or IArrayLike interfaces. // IArrayLike<T> extends IObject<number, T>. Normally only looking for IObject interface // should be enough. But the closure compiler seems to process these two interfaces as if they // were independent. A type can even implements both. for (ObjectType implementedInterface : getAllDirectlyImplementedInterfaces(type)) { String displayName = implementedInterface.getDisplayName(); if ("IObject".equals(displayName)) { List<JSType> iObjectTemplateTypes = implementedInterface.getTemplateTypes(); emitIndexSignature(iObjectTemplateTypes.get(0), iObjectTemplateTypes.get(1), true); } else if ("IArrayLike".equals(displayName)) { emitIndexSignature( compiler.getTypeRegistry().getNativeType(NUMBER_TYPE), implementedInterface.getTemplateTypes().get(0), true); } } // Prototype fields (mostly methods). visitProperties(prototype, false, ((ObjectType) instanceType).getOwnPropertyNames(), superClassFields, classTemplateTypeNames); // Statics are handled in INSTANCE_CLASS_SUFFIX class. unindent(); emit("}"); emitBreak(); } /** * Returns all interfaces implemented by a class and any * superinterface for any of those interfaces. */ public Iterable<ObjectType> getAllDirectlyImplementedInterfaces(FunctionType type) { Set<ObjectType> interfaces = new HashSet<>(); for (ObjectType implementedInterface : type.getOwnImplementedInterfaces()) { addRelatedInterfaces(implementedInterface, interfaces); } return interfaces; } private void addRelatedInterfaces(ObjectType instance, Set<ObjectType> interfaces) { FunctionType constructor = instance.getConstructor(); if (constructor != null && constructor.isInterface() && !interfaces.contains(instance)) { interfaces.add(instance); for (ObjectType interfaceType : instance.getCtorExtendedInterfaces()) { addRelatedInterfaces(interfaceType, interfaces); } } } private void visitProperties(ObjectType objType, boolean isStatic) { visitProperties(objType, isStatic, Collections.<String>emptySet(), Collections.<String>emptySet(), Collections.<String>emptySet()); } private void visitProperties(ObjectType objType, boolean isStatic, Set<String> skipNames, Set<String> forceProps, Set<String> classTemplateTypeNames) { for (String propName : getSortedPropertyNamesToEmit(objType)) { // Extern processing goes through all known symbols, thus statics that are representable as // a namespace, are skipped here and emitted as namespaces only. // (see: extern_static_namespace output.d.ts) if (isExtern && isStatic && isLikelyNamespace(objType.getOwnPropertyJSDocInfo(propName))) continue; if (skipNames.contains(propName)) continue; if ("prototype".equals(propName) || "superClass_".equals(propName) // constructors are handled in #visitObjectType || "constructor".equals(propName)) { continue; } visitProperty(propName, objType, isStatic, forceProps.contains(propName), classTemplateTypeNames); } } /** * Returns the names of props that would be output as fields (not methods) * on superclasses of the given class. */ private Set<String> getSuperClassFields(FunctionType ftype) { Set<String> fields = new LinkedHashSet<>(); ObjectType superType = getSuperType(ftype); // The UNKONWN type has a null constructor. One cannot extend UNKNOWN directly, but this // code can be reached when clutzing a non-closure-valid program. while (superType != null && superType.getConstructor() != null) { aggregateFieldsFromClass(fields, superType); superType = getSuperType(superType.getConstructor()); } return fields; } private void aggregateFieldsFromClass(Set<String> fields, ObjectType superType) { // visit instance properties. for (String field : superType.getOwnPropertyNames()) { if (!superType.getPropertyType(field).isFunctionType()) { fields.add(field); } } // visit prototype properties. if (superType.getConstructor() != null && superType.getConstructor().getPrototype() != null && superType.getConstructor().getPrototype().getOwnPropertyNames() != null) { for (String field : superType.getConstructor().getPrototype().getOwnPropertyNames()) { // getPropertyType works with non-owned property names, i.e. names from the prototype chain. if (!superType.getPropertyType(field).isFunctionType()) { fields.add(field); } } } } private void visitProperty(String propName, ObjectType objType, boolean isStatic, boolean forcePropDeclaration, Set<String> classTemplateTypeNames) { JSType propertyType = objType.getPropertyType(propName); // Some symbols might be emitted as provides, so don't duplicate them String qualifiedName = objType.getDisplayName() + "." + propName; if (provides.contains(qualifiedName)) { return; } else if (isDefiningType(propertyType)) { // enums and classes are emitted in a namespace later. return; } // The static methods from the function prototype are provided by lib.d.ts. if (isStatic && isFunctionPrototypeProp(propName)) return; maybeEmitJsDoc(objType.getOwnPropertyJSDocInfo(propName), /* ignoreParams */ false); emitProperty(propName, propertyType, isStatic, forcePropDeclaration, classTemplateTypeNames); } private void emitProperty(String propName, JSType propertyType, boolean isStatic, boolean forcePropDeclaration, Set<String> classTemplateTypeNames) { if (isStatic) emit("static"); emit(propName); if (!propertyType.isFunctionType() || forcePropDeclaration) { UnionType unionType = propertyType.toMaybeUnionType(); boolean isOptionalProperty = false; if (unionType != null && any(unionType.getAlternates(), isVoidType)) { emit("?"); isOptionalProperty = true; } visitTypeDeclaration(propertyType, false, isOptionalProperty); } else { FunctionType ftype = (FunctionType) propertyType; // Avoid re-emitting template variables defined on the class level if method is not static. Set<String> skipTemplateParams = isStatic ? Collections.<String>emptySet() : classTemplateTypeNames; JSType typeOfThis = ftype.getTypeOfThis(); // If a method returns the 'this' object, it needs to be typed to match the type of the // instance it is invoked on. That way when called on the subclass it should return the // subclass type. // Unfortunately, TypeScript and closure disagree how to type this pattern. // In closure it is a templatized method, together with the @this {T} annotation. // In TypeScript one can use the reserved 'this' type, without templatization. // Detect the pattern here and remove the templatized type from the emit. if (typeOfThis != null && typeOfThis.isTemplateType()) { skipTemplateParams.add(typeOfThis.getDisplayName()); } visitFunctionDeclaration(ftype, skipTemplateParams); } emit(";"); emitBreak(); } private Set<String> getTemplateTypeNames(ObjectType objType) { if (objType.getTemplateTypeMap() == null) { return Collections.emptySet(); } return newHashSet( transform( objType.getTemplateTypeMap().getTemplateKeys(), new Function<JSType, String>() { @Override public String apply(JSType jsType) { return jsType != null ? jsType.getDisplayName() : ""; } })); } private void visitFunctionDeclaration(FunctionType ftype, Set<String> skipTemplateParams) { visitFunctionParameters(ftype, true, skipTemplateParams); JSType type = ftype.getReturnType(); JSType typeOfThis = ftype.getTypeOfThis(); if (type == null) return; emit(":"); // Closure conflates 'undefined' and 'void', and in general visitType always emits `undefined` // for that type. // In ideomatic TypeScript, `void` is used for function return types, and the types // are not strictly the same. if (type.isVoidType()) { emit("void"); } else if (typeOfThis != null && typeOfThis.isTemplateType() && typeOfThis.equals(type)) { // This type is reserved in TypeScript, but a template param in closure. emit("this"); } else { visitType(type); } } private void visitConstructorFunctionDeclaration(FunctionType ftype) { // Translate constructor functions to object type literals with a construct signature. // "function(new:X, string)" --> "{new(a: string): X}". emit("{"); emit("new"); visitFunctionParameters(ftype); emit(":"); visitType(ftype.getInstanceType()); emit("}"); } private void visitFunctionParameters(FunctionType ftype) { visitFunctionParameters(ftype, true, Collections.<String>emptySet()); } private void visitFunctionParameters(FunctionType ftype, boolean emitTemplatizedTypes, Set<String> alreadyEmittedTemplateType) { if (emitTemplatizedTypes) { visitTemplateTypes(ftype, alreadyEmittedTemplateType); } emit("("); Iterator<Node> parameters = ftype.getParameters().iterator(); Iterator<String> names = null; Node functionSource = ftype.getSource(); if (functionSource != null) { // functionSource AST: FUNCTION -> (NAME, PARAM_LIST, BLOCK ...) Iterable<Node> parameterNodes = functionSource.getFirstChild().getNext().children(); names = transform(parameterNodes, NODE_GET_STRING).iterator(); } int paramCount = 0; while (parameters.hasNext()) { Node param = parameters.next(); if (param.isVarArgs()) { emit("..."); } if (names != null && names.hasNext()) { emitNoSpace(names.next()); } else { String pName; if (paramCount < 26) { pName = Character.toString((char) (97 + paramCount)); } else { pName = "p" + (paramCount - 26); } emitNoSpace("" + pName); paramCount++; } if (param.isOptionalArg()) { emit("?"); visitTypeDeclaration(param.getJSType(), param.isVarArgs(), true); } else { visitTypeDeclaration(param.getJSType(), param.isVarArgs(), false); } if (parameters.hasNext()) { emit(", "); } } emit(")"); } void walkInnerSymbols(ObjectType type, String innerNamespace) { // TODO(martinprobst): This curiously duplicates visitProperty above. Investigate the code // smell and reduce duplication (or figure out & document why it's needed). Set<NamedTypePair> innerProps = new TreeSet<>(); // No type means the symbol is a typedef. if (type.isNoType() && childListMap.containsKey(innerNamespace)) { // For typedefs, the inner symbols are not accessible as properties. // We iterate over all symbols to find possible inner symbols. for (TypedVar symbol : childListMap.get(innerNamespace)) { if (getNamespace(symbol.getName()).equals(innerNamespace)) { innerProps.add(new NamedTypePair(symbol.getType(), getUnqualifiedName(symbol.getName()))); } } } else { for (String propName : getSortedPropertyNamesToEmit(type)) { innerProps.add(new NamedTypePair(type.getPropertyType(propName), propName)); } } boolean foundNamespaceMembers = false; for (NamedTypePair namedType : innerProps) { String propName = namedType.name; JSType pType = namedType.type; String qualifiedName = innerNamespace + '.' + propName; if (provides.contains(qualifiedName)) continue; if (pType.isEnumType()) { if (!foundNamespaceMembers) { emitNamespaceBegin(innerNamespace); foundNamespaceMembers = true; } visitEnumType(propName, (EnumType) pType); } else if (isClassLike(pType)) { if (!foundNamespaceMembers) { emitNamespaceBegin(innerNamespace); foundNamespaceMembers = true; } visitClassOrInterface(propName, (FunctionType) pType); } else if (isTypedef(pType)) { if (!foundNamespaceMembers) { emitNamespaceBegin(innerNamespace); foundNamespaceMembers = true; } JSType registryType = typeRegistry.getType(qualifiedName); if (registryType != null) { visitTypeAlias(registryType, propName); } else { emitComment("Intended to visit type alias '" + innerNamespace + "." + propName + " but type not found in Closure type registry."); } // An extra pass is required for interfaces, because in Closure they might have // static methods or fields. TS does not support static methods on interfaces, so we // handle // them here. } else if (type.isInterface() && isOrdinaryFunction(pType)) { // Interfaces are "backed" by a function() {} assignment in closure, // which adds some function prototype methods, that are not truely part of the interface. if (isFunctionPrototypeProp(propName)) continue; if (!foundNamespaceMembers) { emitNamespaceBegin(innerNamespace); foundNamespaceMembers = true; } visitFunctionExpression(propName, (FunctionType) pType); } else if (type.isInterface() && !pType.isNoType() && !pType.isFunctionPrototypeType()) { if (!foundNamespaceMembers) { emitNamespaceBegin(innerNamespace); foundNamespaceMembers = true; } visitVarDeclaration(propName, pType); } } if (foundNamespaceMembers) emitNamespaceEnd(); } private void visitFunctionExpression(String propName, FunctionType ftype) { emit("function"); emit(propName); visitFunctionDeclaration(ftype, Collections.<String>emptySet()); emit(";"); emitBreak(); } public void emitPrivateValue(String emitName) { emit("var"); emit(getUnqualifiedName(emitName)); emit(":"); emit(Constants.INTERNAL_NAMESPACE + ".PrivateType;"); emitBreak(); } public Void emitObjectType(ObjectType type, boolean extendingInstanceClass, boolean inExtendsImplementsPosition) { if (type.getDisplayName() != null && globalSymbolAliases.contains(type.getDisplayName())) { emit("Global" + type.getDisplayName()); return null; } // Closure doesn't require that all the type params be declared, but TS does if (!type.getTemplateTypeMap().isEmpty() && !typeRegistry.getNativeType(OBJECT_TYPE).equals(type)) { return emitTemplatizedType(typeRegistry.createTemplatizedType(type), false, inExtendsImplementsPosition); } if (type.isRecordType()) { visitRecordType((RecordType) type); } else if (type.isDict()) { emit("{[key: string]: any}"); } else if (type.getReferenceName() != null) { String name = getAbsoluteName(type); // Under special conditions (see prototype_inferred_type.js) closure can infer // the type be the prototype object. TypeScript has nothing that matches the shape // of the prototype object (surprisingly typeof A.prototype is A). The best we can do is // any. if (name.endsWith(".prototype")) { emit("any"); return null; } emit(extendingInstanceClass ? name + INSTANCE_CLASS_SUFFIX : name); if (!type.getDisplayName().equals("Object")) { typesUsed.add(type.getDisplayName()); } } else { emit("Object"); } return null; } /** * A type visitor used for types in Foo extends <...> and Foo implements <...> positions. Unlike * the type visitor for a generic type declaration (i.e. var a: <...>), this visitor only emits * symbols that are valid in an extends/implements position. For example: 'class A extends () => * any' is invalid, even though () => any is a valid type. */ class ExtendsImplementsTypeVisitor implements Visitor<Void> { final boolean emitInstanceForObject; ExtendsImplementsTypeVisitor(boolean emitInstanceForObject) { this.emitInstanceForObject = emitInstanceForObject; } @Override public Void caseObjectType(ObjectType type) { emitObjectType(type, emitInstanceForObject, true); return null; } @Override public Void caseUnknownType() { return null; } @Override public Void caseNullType() { return null; } @Override public Void caseNamedType(NamedType type) { return null; } @Override public Void caseProxyObjectType(ProxyObjectType type) { return null; } @Override public Void caseNumberType() { return null; } @Override public Void caseStringType() { return null; } @Override public Void caseVoidType() { return null; } @Override public Void caseUnionType(UnionType type) { return null; } @Override public Void caseTemplatizedType(TemplatizedType type) { emitTemplatizedType(type, emitInstanceForObject, true); return null; } @Override public Void caseTemplateType(TemplateType templateType) { return null; } @Override public Void caseNoType(NoType type) { return null; } @Override public Void caseEnumElementType(EnumElementType type) { return null; } @Override public Void caseAllType() { return null; } @Override public Void caseBooleanType() { return null; } @Override public Void caseNoObjectType() { return null; } @Override public Void caseFunctionType(FunctionType type) { emit("Function"); return null; } } private class NamedTypePair implements Comparable<NamedTypePair> { private final String name; private final JSType type; NamedTypePair(JSType type, String name) { this.type = type; this.name = name; } @Override public int compareTo(NamedTypePair other) { int nameCmp = name.compareTo(other.name); if (nameCmp != 0) return nameCmp; return type.toString().compareTo(other.type.toString()); } } } private boolean isFunctionPrototypeProp(String propName) { switch (propName) { case "apply": case "call": case "bind": return true; default: return false; } } private boolean isOrdinaryFunction(JSType ftype) { // Closure represents top-level functions as classes because they might be new-able. // This happens through externs es3.js which has Function marked as constructor. boolean ordinaryFunctionAppearingAsClass = ftype.isConstructor() && "Function".equals(ftype.getDisplayName()); return ftype.isOrdinaryFunction() || ordinaryFunctionAppearingAsClass; } private boolean isAliasedClassOrInterface(TypedVar symbol, JSType type) { // Confusingly typedefs are constructors. However, they cannot be aliased AFAICT. if (type.isNoType()) return false; if (!type.isConstructor() && !type.isInterface()) return false; return !symbol.getName().equals(type.getDisplayName()); } private void emitSkipTypeAlias(TypedVar symbol) { emit("/* skipped emitting type alias " + symbol.getName() + " to avoid collision with existing one in lib.d.ts. */"); } private boolean isDefinedInPlatformExterns(ObjectType type) { if (type.getConstructor() == null || type.getConstructor().getSource() == null) return false; return isPlatformExtern(type.getConstructor().getSource().getSourceFileName(), type.getDisplayName()); } }
/* * @author <a href="mailto:novotny@aei.mpg.de">Jason Novotny</a> * @version $Id$ */ package org.gridlab.gridsphere.layout; import org.gridlab.gridsphere.portlet.impl.SportletResponse; import org.gridlab.gridsphere.portletcontainer.GridSphereEvent; import java.io.IOException; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Iterator; import java.util.List; public class PortletContainer implements PortletLifecycle { protected int COMPONENT_ID = 0; // The actual portlet layout components protected List components = new ArrayList(); // The component ID's of each of the layout components protected List ComponentIdentifiers = new ArrayList(); // The list of portlets a user has-- generally contained within a PortletFrame/PortletTitleBar combo protected List portlets = new ArrayList(); protected LayoutManager layoutManager; protected String name = ""; public PortletContainer() {} public void setContainerName(String name) { this.name = name; } public String getContainerName() { return name; } public List init(List list) { Iterator it = components.iterator(); PortletLifecycle cycle; ComponentIdentifier compId; while (it.hasNext()) { compId = new ComponentIdentifier(); cycle = (PortletLifecycle)it.next(); compId.setPortletLifecycle(cycle); compId.setClassName(cycle.getClass().getName()); compId.setComponentID(list.size()); list.add(compId); ComponentIdentifiers = cycle.init(list); } System.err.println("Made a components list!!!! " + ComponentIdentifiers.size()); for (int i = 0; i < ComponentIdentifiers.size(); i++) { ComponentIdentifier c = (ComponentIdentifier)ComponentIdentifiers.get(i); System.err.println("id: " + c.getComponentID() + " : " + c.getClassName() + " : " + c.hasPortlet()); } return ComponentIdentifiers; } public void login(GridSphereEvent event) { Iterator it = components.iterator(); PortletLifecycle cycle; while (it.hasNext()) { cycle = (PortletLifecycle)it.next(); cycle.login(event); } } public void logout(GridSphereEvent event) { Iterator it = components.iterator(); PortletLifecycle cycle; while (it.hasNext()) { cycle = (PortletLifecycle)it.next(); cycle.logout(event); } } public void destroy() { Iterator it = components.iterator(); while (it.hasNext()) { PortletComponent comp = (PortletComponent)it.next(); comp.destroy(); } } public void actionPerformed(GridSphereEvent event) throws PortletLayoutException, IOException { // if there is a layout action do it! if (event.hasAction()) { // off by one calculations for array indexing (because all component id's are .size() which is // one more than we use to index the components ComponentIdentifier compId = (ComponentIdentifier)ComponentIdentifiers.get(event.getPortletComponentID() - 1); PortletLifecycle l = compId.getPortletLifecycle(); if (l != null) { l.actionPerformed(event); } } } public void doRender(GridSphereEvent event) throws PortletLayoutException, IOException { SportletResponse res = event.getSportletResponse(); PrintWriter out = res.getWriter(); out.println("<html>"); out.println("<head>"); out.println(" <title>" + name + "</title>"); out.println(" <link type=\"text/css\" href=\"css/default.css\" rel=\"STYLESHEET\"/>"); out.println("</head>\n<body>"); // for css title out.println("<div id=\"page-logo\">" + name + "</div>"); out.println("<div id=\"page-tagline\">Solving the World's Problems!</div>"); ///////////////////////////////////// OLD STUFF ///// //out.println("<html><head><meta HTTP-EQUIV=\"content-type\" CONTENT=\"text/html; charset=ISO-8859-1\">"); //out.println("<title>" + name + "</title>"); Iterator it = components.iterator(); while (it.hasNext()) { PortletRender action = (PortletRender)it.next(); action.doRender(event); } out.println("</body></html>"); } public void setPortletComponents(ArrayList components) { this.components = components; } public List getPortletComponents() { return components; } public List getComponentIdentifierList() { return ComponentIdentifiers; } public void setComponentIdentifierList(List ComponentIdentifiers) { this.ComponentIdentifiers = ComponentIdentifiers; } public int getComponentID() { return COMPONENT_ID; } }
package org.nvonop.selenium.framework.controls; import org.nvonop.selenium.framework.controls.interfaces.Clickable; import org.nvonop.selenium.framework.controls.interfaces.Readable; import org.nvonop.selenium.framework.controls.interfaces.Writeable; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.Keys; /** * This class comprises of functionality that would be used * when interacting with a typical text box control. * @author nvonop * */ public class TextBox extends BaseControl implements Clickable, Readable, Writeable { /** * Constructor that takes a WebDriver object and By object. * These are then set in the base class. * @param driver * @param locator */ public TextBox(WebDriver driver, By locator) { setDriver(driver); setLocator(locator); } /* (non-Javadoc) * @see framework.controls.interfaces.Readable#read() */ @Override public String read() { return getUnderlyingWebElement().getAttribute("value"); } /* (non-Javadoc) * @see framework.controls.interfaces.Clickable#click() */ @Override public void click() { getUnderlyingWebElement().click(); } /* (non-Javadoc) * @see framework.controls.interfaces.Writeable#write(java.lang.String) */ @Override public void write(String value) { getUnderlyingWebElement().sendKeys(Keys.HOME); getUnderlyingWebElement().sendKeys(Keys.SHIFT, Keys.END, Keys.DELETE); getUnderlyingWebElement().sendKeys(value); } /* (non-Javadoc) * @see framework.controls.interfaces.Writeable#write(java.lang.String) */ public void writeWithoutClearingField(String value) { getUnderlyingWebElement().sendKeys(value); } }
package de.uni.freiburg.iig.telematik.wolfgang.menu; import java.io.IOException; import javax.swing.JToggleButton; import javax.swing.JToolBar; import de.invation.code.toval.properties.PropertyException; import de.invation.code.toval.validate.ParameterException; import de.uni.freiburg.iig.telematik.sepia.petrinet.NetType; import de.uni.freiburg.iig.telematik.wolfgang.actions.PopUpToolBarAction; import de.uni.freiburg.iig.telematik.wolfgang.actions.pn.ChecKSoundnessAction; import de.uni.freiburg.iig.telematik.wolfgang.actions.pn.CheckValidityAction; import de.uni.freiburg.iig.telematik.wolfgang.editor.component.PNEditorComponent; import de.uni.freiburg.iig.telematik.wolfgang.exception.EditorToolbarException; import de.uni.freiburg.iig.telematik.wolfgang.menu.toolbars.TokenToolBar; public class CPNToolBar extends AbstractToolBar { // further variables private PNEditorComponent pnEditor = null; private boolean ignoreZoomChange = false; private Mode mode = Mode.EDIT; private enum Mode { EDIT, PLAY } private TokenToolBar tokenToolbar; // private TokenlabelToolBar tokenlabelToolbar; private PopUpToolBarAction tokenAction; private PopUpToolBarAction editTokenlabelAction; // private CheckValidityAction checkValidityAction; // private ChecKSoundnessAction checkSoundnessAction; private JToggleButton tokenButton; // private JToggleButton checkValidityButton; // private JToggleButton checkSoundnessButton; public CPNToolBar(final PNEditorComponent pnEditor, int orientation) throws EditorToolbarException { super(pnEditor, orientation); } @Override protected void addNetSpecificToolbarButtons() { tokenButton = (JToggleButton) add(tokenAction, true); tokenAction.setButton(tokenButton); // checkValidityButton = (JToggleButton) add(checkValidityAction, true); // checkSoundnessButton = (JToggleButton) add(checkSoundnessAction, true); } @Override protected void createAdditionalToolbarActions(PNEditorComponent pnEditor) { try { if (pnEditor.getGraphComponent().getGraph().getNetContainer().getPetriNet().getNetType() == NetType.CPN || pnEditor.getGraphComponent().getGraph().getNetContainer().getPetriNet().getNetType() == NetType.IFNet) { tokenToolbar = new TokenToolBar(pnEditor, JToolBar.HORIZONTAL); tokenAction = new PopUpToolBarAction(pnEditor, "Token", "marking", tokenToolbar); // tokenlabelToolbar = new TokenlabelToolBar(pnEditor, JToolBar.HORIZONTAL); // editTokenlabelAction = new PopUpToolBarAction(pnEditor, "Tokenlabel", "tokenlabel", tokenlabelToolbar); // if (pnEditor.getGraphComponent().getGraph().getNetContainer().getPetriNet().getNetType() == NetType.CPN) { // checkValidityAction = new CheckValidityAction(pnEditor); // checkSoundnessAction = new ChecKSoundnessAction(pnEditor); } } catch (ParameterException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (PropertyException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public void updateGlobalTokenConfigurer() { tokenToolbar.updateView(); } @Override protected void setNetSpecificButtonsVisible(boolean b) { tokenButton.setVisible(b); if (tokenAction.getDialog() != null && tokenButton.isSelected()) tokenAction.getDialog().setVisible(b); } }
package com.hartwig.healthchecks; import java.io.IOException; import java.util.Collection; import java.util.Optional; import org.apache.commons.cli.CommandLine; import org.apache.commons.cli.CommandLineParser; import org.apache.commons.cli.DefaultParser; import org.apache.commons.cli.HelpFormatter; import org.apache.commons.cli.Options; import org.apache.commons.cli.ParseException; import org.apache.logging.log4j.Level; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.jetbrains.annotations.NotNull; import com.hartwig.healthchecks.common.adapter.AbstractHealthCheckAdapter; import com.hartwig.healthchecks.common.adapter.HealthCheckReportFactory; import com.hartwig.healthchecks.common.exception.GenerateReportException; import com.hartwig.healthchecks.common.exception.HealthChecksException; import com.hartwig.healthchecks.common.exception.NotFoundException; import com.hartwig.healthchecks.common.io.dir.FolderChecker; import com.hartwig.healthchecks.common.report.Report; import com.hartwig.healthchecks.util.adapter.HealthChecksFlyweight; import rx.Observable; import rx.observables.BlockingObservable; import rx.schedulers.Schedulers; public class HealthChecksApplication { private static final String RUN_DIR_ARG_DESC = "The path containing the data for a single run"; private static final String CHECK_TYPE_ARGS_DESC = "The type of check to be executed for a single run"; private static final String REPORT_TYPE_ARGS_DESC = "The type of report to be generated: json or stdout."; private static final String REPORT_GENERATED_MSG = "Report generated -> \n%s"; private static final Logger LOGGER = LogManager.getLogger(HealthChecksApplication.class); private static final String RUN_DIRECTORY = "rundir"; private static final String CHECK_TYPE = "checktype"; private static final String REPORT_TYPE = "reporttype"; private static final String ALL_CHECKS = "all"; private final String runDirectory; private final String checkType; private final String reportType; private HealthChecksApplication(@NotNull final String runDirectory, @NotNull final String checkType, @NotNull final String reportType) { this.runDirectory = runDirectory; this.checkType = checkType; this.reportType = reportType; } /** * To Run Healthchecks over files in a dir * * @param args * - Arguments on how to run the health-checks should contain: * -rundir [run-directory] -checktype [boggs - all] -reporttype * [json - stdout] * @throws ParseException * - In case commandline's arguments could not be parsed. */ public static void main(final String... args) throws ParseException { final Options options = createOptions(); final CommandLine cmd = createCommandLine(options, args); String runDirectory = cmd.getOptionValue(RUN_DIRECTORY); final String checkType = cmd.getOptionValue(CHECK_TYPE); final String reportType = cmd.getOptionValue(REPORT_TYPE); if (runDirectory == null || checkType == null || reportType == null) { final HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("Health-Checks", options); System.exit(1); } try { runDirectory = FolderChecker.build().checkFolder(runDirectory); } catch (IOException | HealthChecksException e) { LOGGER.info(e.getMessage()); System.exit(1); } final HealthChecksApplication healthChecksApplication = new HealthChecksApplication(runDirectory, checkType, reportType); healthChecksApplication.processHealthChecks(); } @NotNull private static Options createOptions() { final Options options = new Options(); options.addOption(RUN_DIRECTORY, true, RUN_DIR_ARG_DESC); options.addOption(CHECK_TYPE, true, CHECK_TYPE_ARGS_DESC); options.addOption(REPORT_TYPE, true, REPORT_TYPE_ARGS_DESC); return options; } @NotNull private static CommandLine createCommandLine(@NotNull final Options options, @NotNull final String... args) throws ParseException { final CommandLineParser parser = new DefaultParser(); return parser.parse(options, args); } private void processHealthChecks() { if (checkType.equalsIgnoreCase(ALL_CHECKS)) { executeAllChecks(); } else { final HealthChecksFlyweight flyweight = HealthChecksFlyweight.getInstance(); try { final AbstractHealthCheckAdapter healthCheckAdapter = flyweight.getAdapter(checkType); healthCheckAdapter.runCheck(runDirectory, reportType); } catch (final NotFoundException e) { LOGGER.error(e.getMessage()); } generateReport(); } } private void executeAllChecks() { final HealthChecksFlyweight flyweight = HealthChecksFlyweight.getInstance(); final Collection<AbstractHealthCheckAdapter> adapters = flyweight.getAllAdapters(); final Observable<AbstractHealthCheckAdapter> adapterObservable = Observable.from(adapters) .subscribeOn(Schedulers.io()); BlockingObservable.from(adapterObservable).subscribe(adapter -> adapter.runCheck(runDirectory, reportType), (error) -> LOGGER.error(error.getMessage()), this::generateReport); } private void generateReport() { try { final HealthCheckReportFactory reportFactory = AbstractHealthCheckAdapter.attachReport(reportType); final Report report = reportFactory.create(); final Optional<String> reportData = report.generateReport(runDirectory); if (reportData.isPresent()) { LOGGER.info(String.format(REPORT_GENERATED_MSG, reportData.get())); } } catch (final GenerateReportException e) { LOGGER.log(Level.ERROR, e.getMessage()); } } }
package org.ohmage.request.auth; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.log4j.Logger; import org.ohmage.cache.UserBin; import org.ohmage.request.UserRequest; /** * <p>Removes the user's authentication token from the bin.</p> * * <table border="1"> * <tr> * <td>Parameter Name</td> * <td>Description</td> * <td>Required</td> * </tr> * <tr> * <td>{@value org.ohmage.request.InputKeys#CLIENT}</td> * <td>A string describing the client that is making this request.</td> * <td>true</td> * </tr> * </table> * * @author John Jenkins */ public class AuthTokenLogoutRequest extends UserRequest { private static final Logger LOGGER = Logger.getLogger(AuthTokenLogoutRequest.class); /** * Creates a request for deleting the user's authentication token from the * bin. * * @param httpRequest The HTTP request containing the parameters. */ public AuthTokenLogoutRequest(HttpServletRequest httpRequest) { super(httpRequest, TokenLocation.EITHER); LOGGER.info("Creating a logout request."); } /* * (non-Javadoc) * @see org.ohmage.request.Request#service() */ @Override public void service() { LOGGER.info("Servicing the logout request."); if(! authenticate(AllowNewAccount.NEW_ACCOUNT_DISALLOWED)) { return; } UserBin.expireUser(getUser().getToken()); } /* * (non-Javadoc) * @see org.ohmage.request.Request#respond(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse) */ @Override public void respond(HttpServletRequest httpRequest, HttpServletResponse httpResponse) { LOGGER.info("Responding to the logout request."); respond(httpRequest, httpResponse, null); } }
package com.lazerycode.selenium.download; import com.lazerycode.selenium.extract.BinaryFileNames; import com.lazerycode.selenium.extract.ExtractFilesFromArchive; import com.lazerycode.selenium.hash.HashType; import com.lazerycode.selenium.repository.FileDetails; import org.apache.commons.codec.digest.DigestUtils; import org.apache.commons.io.FilenameUtils; import org.apache.log4j.Logger; import org.apache.maven.plugin.MojoExecutionException; import org.apache.maven.plugin.MojoFailureException; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.util.Map; import static org.apache.commons.io.FileUtils.copyURLToFile; public class DownloadHandler { private static final Logger LOG = Logger.getLogger(DownloadHandler.class); private final File rootStandaloneServerDirectory; private final File downloadedZipFileDirectory; private final int fileDownloadReadTimeout; private final int fileDownloadConnectTimeout; private final Map<String, FileDetails> filesToDownload; final int fileDownloadRetryAttempts; private boolean overwriteFilesThatExist = false; private boolean checkFileHash = true; public DownloadHandler(File rootStandaloneServerDirectory, File downloadedZipFileDirectory, int fileDownloadRetryAttempts, int fileDownloadConnectTimeout, int fileDownloadReadTimeout, Map<String, FileDetails> filesToDownload, boolean overwriteFilesThatExist, boolean checkFileHash) { this.rootStandaloneServerDirectory = rootStandaloneServerDirectory; this.downloadedZipFileDirectory = downloadedZipFileDirectory; if (fileDownloadRetryAttempts < 1) { LOG.warn("Invalid number of retry attempts specified, defaulting to '1'..."); this.fileDownloadRetryAttempts = 1; } else { this.fileDownloadRetryAttempts = fileDownloadRetryAttempts; } this.fileDownloadConnectTimeout = fileDownloadConnectTimeout; this.fileDownloadReadTimeout = fileDownloadReadTimeout; this.filesToDownload = filesToDownload; this.overwriteFilesThatExist = overwriteFilesThatExist; this.checkFileHash = checkFileHash; } public void getStandaloneExecutableFiles() throws Exception { LOG.info("Archives will be downloaded to '" + this.downloadedZipFileDirectory.getAbsolutePath() + "'"); LOG.info("Standalone executable files will be extracted to '" + this.rootStandaloneServerDirectory + "'"); LOG.info(" "); LOG.info("Preparing to download Selenium Standalone Executable Binaries..."); LOG.info(" "); File fileToUnzip; for (Map.Entry<String, FileDetails> fileToDownload : this.filesToDownload.entrySet()) { LOG.info(" "); String currentFileAbsolutePath = this.downloadedZipFileDirectory + File.separator + FilenameUtils.getName(fileToDownload.getValue().getFileLocation().getFile()); LOG.info("Checking to see if archive file '" + currentFileAbsolutePath + "' already exists and is valid."); boolean existsAndIsValid = fileExistsAndIsValid(new File(currentFileAbsolutePath), fileToDownload.getValue().getHash(), fileToDownload.getValue().getHashType()); if (!existsAndIsValid) { fileToUnzip = downloadFile(fileToDownload.getValue()); } else { fileToUnzip = new File(currentFileAbsolutePath); } String extractionDirectory = this.rootStandaloneServerDirectory.getAbsolutePath() + File.separator + fileToDownload.getKey(); String binaryForOperatingSystem = fileToDownload.getKey().replace("\\", "/").split("/")[1].toUpperCase(); //TODO should really store the OS we have extracted somewhere rather than doing this hack! LOG.debug("Detected a binary for OS: " + binaryForOperatingSystem); if (ExtractFilesFromArchive.extractFileFromArchive(fileToUnzip, extractionDirectory, this.overwriteFilesThatExist, BinaryFileNames.valueOf(binaryForOperatingSystem))) { LOG.info("File(s) copied to " + extractionDirectory); } } } /** * Perform the file download * * @return File * @throws MojoExecutionException */ File downloadFile(FileDetails fileDetails) throws Exception { String filename = FilenameUtils.getName(fileDetails.getFileLocation().getFile()); File fileToDownload = new File(localFilePath(this.downloadedZipFileDirectory) + File.separator + filename); for (int n = 0; n < this.fileDownloadRetryAttempts; n++) { try { LOG.info("Downloading '" + filename + "'..."); copyURLToFile(fileDetails.getFileLocation(), fileToDownload, this.fileDownloadConnectTimeout, this.fileDownloadReadTimeout); LOG.info("Checking to see if downloaded copy of '" + fileToDownload.getName() + "' is valid."); if (fileExistsAndIsValid(fileToDownload, fileDetails.getHash(), fileDetails.getHashType())) return fileToDownload; } catch (IOException ex) { LOG.info("Problem downloading '" + fileToDownload.getName() + "'... " + ex.getLocalizedMessage()); if (n + 1 < this.fileDownloadRetryAttempts) LOG.info("Trying to download'" + fileToDownload.getName() + "' again..."); } } LOG.error("Unable to successfully downloaded '" + fileToDownload.getName() + "'!"); throw new MojoExecutionException("Unable to successfully downloaded '" + fileToDownload.getName() + "'!"); } /** * Set the location directory where files will be downloaded to/ * * @param downloadDirectory The directory that the file will be downloaded to. */ private String localFilePath(File downloadDirectory) throws MojoFailureException { if (!downloadDirectory.exists()) { if (!downloadDirectory.mkdirs()) { throw new MojoFailureException("Unable to create download directory!"); } } if (!downloadDirectory.isDirectory()) { throw new MojoFailureException("'" + downloadDirectory.getAbsolutePath() + "' is not a directory!"); } return downloadDirectory.getAbsolutePath(); } /** * Check if the file exists and perform a Hash check on it to see if it is valid * * @param fileToCheck the file to perform a hash validation against * @return true if the file exists and is valid * @throws IOException */ boolean fileExistsAndIsValid(File fileToCheck, String expectedHash, HashType hashType) throws IOException, MojoExecutionException { if (!fileToCheck.exists()) return false; if (!checkFileHash) return true; if (null == expectedHash) { throw new MojoExecutionException("The hash for " + fileToCheck.getName() + " is missing from your RepositoryMap.xml"); } else if (null == hashType) { throw new MojoExecutionException("The hashtype for " + fileToCheck.getName() + " is missing from your RepositoryMap.xml"); } String actualFileHash; FileInputStream fileToHashCheck = new FileInputStream(fileToCheck); switch (hashType) { case MD5: actualFileHash = DigestUtils.md5Hex(fileToHashCheck); break; case SHA1: default: actualFileHash = DigestUtils.shaHex(fileToHashCheck); break; } fileToHashCheck.close(); return actualFileHash.equals(expectedHash); } }
package org.opencms.ade.configuration; import org.opencms.ade.configuration.formatters.CmsFormatterChangeSet; import org.opencms.ade.configuration.formatters.CmsFormatterConfigurationCacheState; import org.opencms.ade.detailpage.CmsDetailPageInfo; import org.opencms.file.CmsObject; import org.opencms.file.CmsResource; import org.opencms.file.types.CmsResourceTypeFolder; import org.opencms.file.types.CmsResourceTypeXmlContent; import org.opencms.file.types.I_CmsResourceType; import org.opencms.loader.CmsLoaderException; import org.opencms.main.CmsException; import org.opencms.main.CmsLog; import org.opencms.main.OpenCms; import org.opencms.util.CmsStringUtil; import org.opencms.util.CmsUUID; import org.opencms.xml.CmsXmlContentDefinition; import org.opencms.xml.containerpage.CmsFormatterConfiguration; import org.opencms.xml.containerpage.I_CmsFormatterBean; import org.opencms.xml.content.CmsXmlContentProperty; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Set; import org.apache.commons.logging.Log; import com.google.common.collect.ComparisonChain; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.google.common.collect.Sets; /** * A class which represents the accessible configuration data at a given point in a sitemap.<p> */ public class CmsADEConfigData { /** The log instance for this class. */ private static final Log LOG = CmsLog.getLog(CmsADEConfigData.class); /** The "create contents locally" flag. */ protected boolean m_createContentsLocally; /** Should inherited model pages be discarded? */ protected boolean m_discardInheritedModelPages; /** Should inherited properties be discard? */ protected boolean m_discardInheritedProperties; /** Should inherited types be discarded? */ protected boolean m_discardInheritedTypes; /** The base path of this configuration. */ private String m_basePath; /** The cms context used for reading the configuration data. */ private CmsObject m_cms; /** The configured formatter changes. */ private CmsFormatterChangeSet m_formatterChangeSet; /** The list of configured function references. */ private List<CmsFunctionReference> m_functionReferences = new ArrayList<CmsFunctionReference>(); /** A flag which keeps track of whether this instance has already been initialized. */ private boolean m_initialized; /** True if this is a module configuration, not a normal sitemap configuration. */ private boolean m_isModuleConfig; /** The internal detail page configuration. */ private List<CmsDetailPageInfo> m_ownDetailPages = new ArrayList<CmsDetailPageInfo>(); /** The internal model page entries. */ private List<CmsModelPageConfig> m_ownModelPageConfig = new ArrayList<CmsModelPageConfig>(); /** The internal property configuration. */ private List<CmsPropertyConfig> m_ownPropertyConfigurations = new ArrayList<CmsPropertyConfig>(); /** The internal resource type entries. */ private List<CmsResourceTypeConfig> m_ownResourceTypes = new ArrayList<CmsResourceTypeConfig>(); /** The resource from which the configuration data was read. */ private CmsResource m_resource; /** * Default constructor to create an empty configuration.<p> */ public CmsADEConfigData() { // do nothing } /** * Creates an empty configuration data object with a given base path.<p> * * @param basePath the base path */ public CmsADEConfigData(String basePath) { m_basePath = basePath; } /** * Creates a new configuration data instance.<p> * * @param basePath the base path * @param resourceTypeConfig the resource type configuration * @param discardInheritedTypes the "discard inherited types" flag * @param propertyConfig the property configuration * @param discardInheritedProperties the "discard inherited properties" flag * @param detailPageInfos the detail page configuration * @param modelPages the model page configuration * @param functionReferences the function reference configuration * @param discardInheritedModelPages the "discard inherited model pages" flag * @param createContentsLocally the "create contents locally" flag * @param formatterChangeSet the formatter changes */ public CmsADEConfigData( String basePath, List<CmsResourceTypeConfig> resourceTypeConfig, boolean discardInheritedTypes, List<CmsPropertyConfig> propertyConfig, boolean discardInheritedProperties, List<CmsDetailPageInfo> detailPageInfos, List<CmsModelPageConfig> modelPages, List<CmsFunctionReference> functionReferences, boolean discardInheritedModelPages, boolean createContentsLocally, CmsFormatterChangeSet formatterChangeSet) { m_basePath = basePath; m_ownResourceTypes = resourceTypeConfig; m_ownPropertyConfigurations = propertyConfig; m_ownModelPageConfig = modelPages; m_ownDetailPages = detailPageInfos; m_functionReferences = functionReferences; m_discardInheritedTypes = discardInheritedTypes; m_discardInheritedProperties = discardInheritedProperties; m_discardInheritedModelPages = discardInheritedModelPages; m_createContentsLocally = createContentsLocally; m_formatterChangeSet = formatterChangeSet; } /** * Creates an empty configuration for a given base path.<p> * * @param basePath the base path * * @return the empty configuration object */ public static CmsADEConfigData emptyConfiguration(String basePath) { return new CmsADEConfigData(basePath); } /** * Generic method to merge lists of named configuration objects.<p> * * The lists are merged such that the configuration objects from the child list rise to the front of the result list, * and two configuration objects will be merged themselves if they share the same name.<p> * * For example, if we have two lists of configuration objects:<p> * * parent: A1, B1, C1<p> * child: D2, B2<p> * * then the resulting list will look like:<p> * * D2, B3, A1, C1<p> * * where B3 is the result of merging B1 and B2.<p> * * @param <C> the type of configuration object * @param parentConfigs the parent configurations * @param childConfigs the child configurations * @return the merged configuration object list */ protected static <C extends I_CmsConfigurationObject<C>> List<C> combineConfigurationElements( List<C> parentConfigs, List<C> childConfigs) { List<C> result = new ArrayList<C>(); Map<String, C> map = new LinkedHashMap<String, C>(); if (parentConfigs != null) { for (C parent : Lists.reverse(parentConfigs)) { map.put(parent.getKey(), parent); } } if (childConfigs == null) { childConfigs = Collections.emptyList(); } for (C child : Lists.reverse(childConfigs)) { String childKey = child.getKey(); if (child.isDisabled()) { map.remove(childKey); } else { C parent = map.get(childKey); map.remove(childKey); C newValue; if (parent != null) { newValue = parent.merge(child); } else { newValue = child; } map.put(childKey, newValue); } } result = new ArrayList<C>(map.values()); Collections.reverse(result); // those multiple "reverse" calls may a bit confusing. They are there because on the one hand we want to keep the // configuration items from one configuration in the same order as they are defined, on the other hand we want // configuration items from a child configuration to rise to the top of the configuration items. // so for example, if the parent configuration has items with the keys A,B,C,E // and the child configuration has items with the keys C,B,D // we want the items of the combined configuration in the order C,B,D,A,E return result; } /** * Applies the formatter change sets of this and all parent configurations to a map of external (non-schema) formatters.<p> * * @param formatters the external formatter map which will be modified * * @param formatterCacheState the formatter cache state from which new external formatters should be fetched */ public void applyAllFormatterChanges( Map<CmsUUID, I_CmsFormatterBean> formatters, CmsFormatterConfigurationCacheState formatterCacheState) { for (CmsFormatterChangeSet changeSet : getFormatterChangeSets()) { changeSet.applyToFormatters(formatters, formatterCacheState); } } /** * Gets the active external (non-schema) formatters for this sub-sitemap.<p> * * @return the map of active external formatters by structure id */ public Map<CmsUUID, I_CmsFormatterBean> getActiveFormatters() { CmsFormatterConfigurationCacheState cacheState = OpenCms.getADEManager().getCachedFormatters( m_cms.getRequestContext().getCurrentProject().isOnlineProject()); Map<CmsUUID, I_CmsFormatterBean> result = Maps.newHashMap(cacheState.getAutoEnabledFormatters()); applyAllFormatterChanges(result, cacheState); return result; } /** * Gets the list of all detail pages.<p> * * @return the list of all detail pages */ public List<CmsDetailPageInfo> getAllDetailPages() { return getAllDetailPages(true); } /** * Gets a list of all detail pages.<p> * * @param update if true, this method will try to correct the root paths in the returned objects if the corresponding resources have been moved * * @return the list of all detail pages */ public List<CmsDetailPageInfo> getAllDetailPages(boolean update) { checkInitialized(); CmsADEConfigData parentData = parent(); List<CmsDetailPageInfo> parentDetailPages; if (parentData != null) { parentDetailPages = parentData.getAllDetailPages(false); } else { parentDetailPages = Collections.emptyList(); } List<CmsDetailPageInfo> result = mergeDetailPages(parentDetailPages, m_ownDetailPages); if (update) { result = updateUris(result); } return result; } /** * Gets the configuration base path.<p> * * For example, if the configuration file is located at /sites/default/.content/.config, the base path is /sites/default.<p> * * @return the base path of the configuration */ public String getBasePath() { checkInitialized(); return m_basePath; } /** * Gets the content folder path.<p> * * For example, if the configuration file is located at /sites/default/.content/.config, the content folder path is /sites/default/.content * * @return the content folder path */ public String getContentFolderPath() { return CmsStringUtil.joinPaths(m_basePath, CmsADEManager.CONTENT_FOLDER_NAME); } /** * Returns a list of the creatable resource types.<p> * * @param cms the CMS context used to check whether the resource types are creatable * @return the list of creatable resource type * * @throws CmsException if something goes wrong */ public List<CmsResourceTypeConfig> getCreatableTypes(CmsObject cms) throws CmsException { checkInitialized(); List<CmsResourceTypeConfig> result = new ArrayList<CmsResourceTypeConfig>(); for (CmsResourceTypeConfig typeConfig : getResourceTypes()) { if (typeConfig.checkCreatable(cms)) { result.add(typeConfig); } } return result; } /** * Returns the default model page.<p> * * @return the default model page */ public CmsModelPageConfig getDefaultModelPage() { checkInitialized(); List<CmsModelPageConfig> modelPages = getModelPages(); for (CmsModelPageConfig modelPageConfig : getModelPages()) { if (modelPageConfig.isDefault()) { return modelPageConfig; } } if (modelPages.isEmpty()) { return null; } return modelPages.get(0); } /** * Gets the detail pages for a specific type.<p> * * @param type the type name * * @return the list of detail pages for that type */ public List<CmsDetailPageInfo> getDetailPagesForType(String type) { List<CmsDetailPageInfo> result = new ArrayList<CmsDetailPageInfo>(); for (CmsDetailPageInfo detailpage : getAllDetailPages(true)) { if (detailpage.getType().equals(type)) { result.add(detailpage); } } return result; } /** * Returns the formatter change sets for this and all parent sitemaps, ordered by increasing folder depth of the sitemap.<p> * * @return the formatter change sets for all ancestor sitemaps */ public List<CmsFormatterChangeSet> getFormatterChangeSets() { CmsADEConfigData currentConfig = this; List<CmsFormatterChangeSet> result = Lists.newArrayList(); while (currentConfig != null) { CmsFormatterChangeSet changes = currentConfig.getOwnFormatterChangeSet(); result.add(changes); currentConfig = currentConfig.parent(); } Collections.reverse(result); return result; } /** * Gets the formatter configuration for a resource.<p> * * @param cms the current CMS context * @param res the resource for which the formatter configuration should be retrieved * * @return the configuration of formatters for the resource */ public CmsFormatterConfiguration getFormatters(CmsObject cms, CmsResource res) { int resTypeId = res.getTypeId(); try { I_CmsResourceType resType = OpenCms.getResourceManager().getResourceType(resTypeId); String typeName = resType.getTypeName(); CmsFormatterConfigurationCacheState formatterCacheState = OpenCms.getADEManager().getCachedFormatters( cms.getRequestContext().getCurrentProject().isOnlineProject()); CmsFormatterConfiguration schemaFormatters = getFormattersFromSchema(cms, res); List<I_CmsFormatterBean> formatters = new ArrayList<I_CmsFormatterBean>(); Set<String> types = new HashSet<String>(); types.add(typeName); for (CmsFormatterChangeSet changeSet : getFormatterChangeSets()) { changeSet.applyToTypes(types); } if (types.contains(typeName)) { for (I_CmsFormatterBean formatter : schemaFormatters.getAllFormatters()) { formatters.add(formatter); } } Map<CmsUUID, I_CmsFormatterBean> externalFormattersById = Maps.newHashMap(); for (I_CmsFormatterBean formatter : formatterCacheState.getFormattersForType(typeName, true)) { externalFormattersById.put(new CmsUUID(formatter.getId()), formatter); } applyAllFormatterChanges(externalFormattersById, formatterCacheState); for (I_CmsFormatterBean formatter : externalFormattersById.values()) { if (typeName.equals(formatter.getResourceTypeName())) { formatters.add(formatter); } } return CmsFormatterConfiguration.create(cms, formatters); } catch (CmsLoaderException e) { LOG.warn(e.getLocalizedMessage(), e); return null; } } /** * Gets a named function reference.<p> * * @param name the name of the function reference * * @return the function reference for the given name */ public CmsFunctionReference getFunctionReference(String name) { List<CmsFunctionReference> functionReferences = getFunctionReferences(); for (CmsFunctionReference functionRef : functionReferences) { if (functionRef.getName().equals(name)) { return functionRef; } } return null; } /** * Gets the list of configured function references.<p> * * @return the list of configured function references */ public List<CmsFunctionReference> getFunctionReferences() { return internalGetFunctionReferences(); } /** * Gets the map of external (non-schema) formatters which are inactive in this sub-sitemap.<p> * * @return the map inactive external formatters */ public Map<CmsUUID, I_CmsFormatterBean> getInactiveFormatters() { CmsFormatterConfigurationCacheState cacheState = OpenCms.getADEManager().getCachedFormatters( m_cms.getRequestContext().getCurrentProject().isOnlineProject()); Map<CmsUUID, I_CmsFormatterBean> result = Maps.newHashMap(cacheState.getFormatters()); result.keySet().removeAll(getActiveFormatters().keySet()); return result; } /** * Gets the main detail page for a specific type.<p> * * @param type the type name * * @return the main detail page for that type */ public CmsDetailPageInfo getMainDetailPage(String type) { List<CmsDetailPageInfo> detailPages = getDetailPagesForType(type); if ((detailPages == null) || detailPages.isEmpty()) { return null; } return detailPages.get(0); } /** * Gets the list of available model pages.<p> * * @return the list of available model pages */ public List<CmsModelPageConfig> getModelPages() { CmsADEConfigData parentData = parent(); List<CmsModelPageConfig> parentModelPages; if ((parentData != null) && !m_discardInheritedModelPages) { parentModelPages = parentData.getModelPages(); } else { parentModelPages = Collections.emptyList(); } List<CmsModelPageConfig> result = combineConfigurationElements(parentModelPages, m_ownModelPageConfig); return result; } /** * Gets the formatter changes for this sitemap configuration.<p> * * @return the formatter change set */ public CmsFormatterChangeSet getOwnFormatterChangeSet() { return m_formatterChangeSet; } /** * Gets the configuration for the available properties.<p> * * @return the configuration for the available properties */ public List<CmsPropertyConfig> getPropertyConfiguration() { CmsADEConfigData parentData = parent(); List<CmsPropertyConfig> parentProperties; if ((parentData != null) && !m_discardInheritedProperties) { parentProperties = parentData.getPropertyConfiguration(); } else { parentProperties = Collections.emptyList(); } List<CmsPropertyConfig> result = combineConfigurationElements(parentProperties, m_ownPropertyConfigurations); return result; } /** * Gets the property configuration as a map of CmsXmlContentProperty instances.<p> * * @return the map of property configurations */ public Map<String, CmsXmlContentProperty> getPropertyConfigurationAsMap() { Map<String, CmsXmlContentProperty> result = new LinkedHashMap<String, CmsXmlContentProperty>(); for (CmsPropertyConfig propConf : getPropertyConfiguration()) { result.put(propConf.getName(), propConf.getPropertyData()); } return result; } /** * Returns the resource from which this configuration was read.<p> * * @return the resource from which this configuration was read */ public CmsResource getResource() { return m_resource; } /** * Returns the configuration for a specific resource type.<p> * * @param typeName the name of the type * * @return the resource type configuration for that type */ public CmsResourceTypeConfig getResourceType(String typeName) { checkInitialized(); for (CmsResourceTypeConfig type : getResourceTypes()) { if (typeName.equals(type.getTypeName())) { return type; } } return null; } /** * Gets a list of all available resource type configurations.<p> * * @return the available resource type configurations */ public List<CmsResourceTypeConfig> getResourceTypes() { List<CmsResourceTypeConfig> result = internalGetResourceTypes(); for (CmsResourceTypeConfig config : result) { config.initialize(m_cms); } return result; } /** * Gets the searchable resource type configurations.<p> * * @param cms the current CMS context * @return the searchable resource type configurations */ public Collection<CmsResourceTypeConfig> getSearchableTypes(CmsObject cms) { return getResourceTypes(); } /** * Gets the set of resource type names for which schema formatters can be enabled or disabled and which are not disabled in this sub-sitemap.<p> * * @return the set of types for which schema formatters are active */ public Set<String> getTypesWithActiveSchemaFormatters() { Set<String> result = Sets.newHashSet(getTypesWithModifiableFormatters()); for (CmsFormatterChangeSet changeSet : getFormatterChangeSets()) { changeSet.applyToTypes(result); } return result; } /** * Gets the set of names of resource types which have schema-based formatters that can be enabled or disabled.<p> * * @return the set of names of resource types which have schema-based formatters that can be enabled or disabled */ public Set<String> getTypesWithModifiableFormatters() { Set<String> result = new HashSet<String>(); for (I_CmsResourceType type : OpenCms.getResourceManager().getResourceTypes()) { if (type instanceof CmsResourceTypeXmlContent) { CmsXmlContentDefinition contentDef = null; try { contentDef = CmsXmlContentDefinition.getContentDefinitionForType(m_cms, type.getTypeName()); if ((contentDef != null) && contentDef.getContentHandler().hasModifiableFormatters()) { result.add(type.getTypeName()); } } catch (Exception e) { LOG.error(e.getLocalizedMessage(), e); } } } return result; } /** * Initializes the configuration object.<p> * * @param cms the CMS context to be used for VFS operations */ public void initialize(CmsObject cms) { m_cms = cms; m_initialized = true; } /** * Returns the value of the "create contents locally" flag.<p> * * If this flag is set, contents of types configured in a super-sitemap will be created in the sub-sitemap (if the user * creates them from the sub-sitemap). * * @return the "create contents locally" flag */ public boolean isCreateContentsLocally() { return m_createContentsLocally; } /** * Returns the value of the "discard inherited model pages" flag.<p> * * If this flag is set, inherited model pages will be discarded for this sitemap.<p> * * @return the "discard inherited model pages" flag */ public boolean isDiscardInheritedModelPages() { return m_discardInheritedModelPages; } /** * Returns the value of the "discard inherited properties" flag.<p> * * If this is flag is set, inherited property definitions will be discarded for this sitemap.<p> * * @return the "discard inherited properties" flag.<p> */ public boolean isDiscardInheritedProperties() { return m_discardInheritedProperties; } /** * Returns the value of the "discard inherited types" flag.<p> * * If this flag is set, inherited resource types from a super-sitemap will be discarded for this sitemap.<p> * * @return the "discard inherited types" flag */ public boolean isDiscardInheritedTypes() { return m_discardInheritedTypes; } /** * Returns true if this is a module configuration instead of a normal sitemap configuration.<p> * * @return true if this is a module configuration */ public boolean isModuleConfiguration() { return m_isModuleConfig; } /** * Fetches the parent configuration of this configuration.<p> * * If this configuration is a sitemap configuration with no direct parent configuration, * the module configuration will be returned. If this configuration already is a module configuration, * null will be returned.<p> * * @return the parent configuration */ public CmsADEConfigData parent() { if (m_basePath == null) { return null; } String parentPath = CmsResource.getParentFolder(m_basePath); if (OpenCms.getADEManager() == null) { return null; } CmsADEConfigData result = OpenCms.getADEManager().internalLookupConfiguration(m_cms, parentPath); return result; } /** * Sets the "module configuration" flag.<p> * * @param isModuleConfig true if this configuration should be marked as a module configuration */ public void setIsModuleConfig(boolean isModuleConfig) { checkNotInitialized(); m_isModuleConfig = isModuleConfig; } /** * Sets the configuration file resource.<p> * * @param resource the configuration file resource */ public void setResource(CmsResource resource) { checkNotInitialized(); m_resource = resource; } /** * Checks whether the configuration is initialized and throws an error otherwise.<p> */ protected void checkInitialized() { if (!m_initialized) { throw new IllegalStateException(); } } /** * Checks whether the configuration is *NOT* initialized and throws an error otherwise.<p> */ protected void checkNotInitialized() { if (m_initialized) { throw new IllegalStateException(); } } /** * Creates the content directory for this configuration node if possible.<p> * * @throws CmsException if something goes wrong */ protected void createContentDirectory() throws CmsException { if (!isModuleConfiguration()) { String contentFolder = getContentFolderPath(); if (!m_cms.existsResource(contentFolder)) { m_cms.createResource( contentFolder, OpenCms.getResourceManager().getResourceType(CmsResourceTypeFolder.getStaticTypeName()).getTypeId()); } } } /** * Gets the CMS object used for VFS operations.<p> * * @return the CMS object */ protected CmsObject getCmsObject() { return m_cms; } /** * Helper method to converts a list of detail pages to a map from type names to lists of detail pages for each type.<p> * * @param detailPages the list of detail pages * * @return the map of detail pages */ protected Map<String, List<CmsDetailPageInfo>> getDetailPagesMap(List<CmsDetailPageInfo> detailPages) { Map<String, List<CmsDetailPageInfo>> result = Maps.newHashMap(); for (CmsDetailPageInfo detailpage : detailPages) { String type = detailpage.getType(); if (!result.containsKey(type)) { result.put(type, new ArrayList<CmsDetailPageInfo>()); } result.get(type).add(detailpage); } return result; } /** * Collects the folder types in a map.<p> * * @return the map of folder types * * @throws CmsException if something goes wrong */ protected Map<String, String> getFolderTypes() throws CmsException { Map<String, String> result = new HashMap<String, String>(); CmsObject cms = OpenCms.initCmsObject(m_cms); if (m_isModuleConfig) { Set<String> siteRoots = OpenCms.getSiteManager().getSiteRoots(); for (String siteRoot : siteRoots) { cms.getRequestContext().setSiteRoot(siteRoot); for (CmsResourceTypeConfig config : getResourceTypes()) { String typeName = config.getTypeName(); String folderPath = config.getFolderPath(cms); result.put(CmsStringUtil.joinPaths(folderPath, "/"), typeName); } } } else { for (CmsResourceTypeConfig config : getResourceTypes()) { String typeName = config.getTypeName(); String folderPath = config.getFolderPath(m_cms); result.put(CmsStringUtil.joinPaths(folderPath, "/"), typeName); } } return result; } /** * Gets the formatters from the schema.<p> * * @param cms the current CMS context * @param res the resource for which the formatters should be retrieved * * @return the formatters from the schema */ protected CmsFormatterConfiguration getFormattersFromSchema(CmsObject cms, CmsResource res) { try { return OpenCms.getResourceManager().getResourceType(res.getTypeId()).getFormattersForResource(cms, res); } catch (CmsException e) { LOG.error(e.getLocalizedMessage(), e); return CmsFormatterConfiguration.EMPTY_CONFIGURATION; } } /** * Internal method for getting the function references.<p> * * @return the function references */ protected List<CmsFunctionReference> internalGetFunctionReferences() { checkInitialized(); CmsADEConfigData parentData = parent(); if ((parentData == null)) { if (m_isModuleConfig) { return Collections.unmodifiableList(m_functionReferences); } else { return Lists.newArrayList(); } } else { return parentData.internalGetFunctionReferences(); } } /** * Helper method for getting the list of resource types.<p> * * @return the list of resource types */ protected List<CmsResourceTypeConfig> internalGetResourceTypes() { checkInitialized(); CmsADEConfigData parentData = parent(); List<CmsResourceTypeConfig> parentResourceTypes = null; if ((parentData == null) || m_discardInheritedTypes) { parentResourceTypes = Lists.newArrayList(); } else { parentResourceTypes = Lists.newArrayList(); for (CmsResourceTypeConfig typeConfig : parentData.internalGetResourceTypes()) { parentResourceTypes.add(typeConfig.copy()); } } List<CmsResourceTypeConfig> result = combineConfigurationElements(parentResourceTypes, m_ownResourceTypes); if (m_createContentsLocally) { for (CmsResourceTypeConfig typeConfig : result) { typeConfig.updateBasePath(CmsStringUtil.joinPaths(m_basePath, CmsADEManager.CONTENT_FOLDER_NAME)); } } return result; } /** * Merges two lists of detail pages, one from a parent configuration and one from a child configuration.<p> * * @param parentDetailPages the parent's detail pages * @param ownDetailPages the child's detail pages * * @return the merged detail pages */ protected List<CmsDetailPageInfo> mergeDetailPages( List<CmsDetailPageInfo> parentDetailPages, List<CmsDetailPageInfo> ownDetailPages) { List<CmsDetailPageInfo> result = new ArrayList<CmsDetailPageInfo>(); Map<String, List<CmsDetailPageInfo>> resultDetailPageMap = Maps.newHashMap(); resultDetailPageMap.putAll(getDetailPagesMap(parentDetailPages)); resultDetailPageMap.putAll(getDetailPagesMap(ownDetailPages)); result = new ArrayList<CmsDetailPageInfo>(); for (List<CmsDetailPageInfo> pages : resultDetailPageMap.values()) { result.addAll(pages); } return result; } /** * Merges the parent's data into this object.<p> * * @param parent the parent configuration data */ protected void mergeParent(CmsADEConfigData parent) { List<CmsResourceTypeConfig> parentTypes = null; if (parent != null) { parentTypes = parent.m_ownResourceTypes; } else { parentTypes = Collections.emptyList(); } List<CmsPropertyConfig> parentProperties = null; if (parent != null) { parentProperties = parent.m_ownPropertyConfigurations; } else { parentProperties = Collections.emptyList(); } List<CmsModelPageConfig> parentModelPages = null; if (parent != null) { parentModelPages = parent.m_ownModelPageConfig; } else { parentModelPages = Collections.emptyList(); } List<CmsFunctionReference> parentFunctionRefs = null; if (parent != null) { parentFunctionRefs = parent.m_functionReferences; } else { parentFunctionRefs = Collections.emptyList(); } m_ownResourceTypes = combineConfigurationElements(parentTypes, m_ownResourceTypes); m_ownPropertyConfigurations = combineConfigurationElements(parentProperties, m_ownPropertyConfigurations); m_ownModelPageConfig = combineConfigurationElements(parentModelPages, m_ownModelPageConfig); m_functionReferences = combineConfigurationElements(parentFunctionRefs, m_functionReferences); } /** * Handle the ordering from the module configurations.<p> */ protected void processModuleOrdering() { Collections.sort(m_ownResourceTypes, new Comparator<CmsResourceTypeConfig>() { public int compare(CmsResourceTypeConfig a, CmsResourceTypeConfig b) { return ComparisonChain.start().compare(a.getOrder(), b.getOrder()).compare( a.getTypeName(), b.getTypeName()).result(); } }); Collections.sort(m_ownPropertyConfigurations, new Comparator<CmsPropertyConfig>() { public int compare(CmsPropertyConfig a, CmsPropertyConfig b) { return ComparisonChain.start().compare(a.getOrder(), b.getOrder()).compare(a.getName(), b.getName()).result(); } }); Collections.sort(m_functionReferences, new Comparator<CmsFunctionReference>() { public int compare(CmsFunctionReference a, CmsFunctionReference b) { return ComparisonChain.start().compare(a.getOrder(), b.getOrder()).compare(a.getName(), b.getName()).result(); } }); } /** * Helper method to correct paths in detail page beans if the corresponding resources have been moved.<p> * * @param detailPages the original list of detail pages * * @return the corrected list of detail pages */ protected List<CmsDetailPageInfo> updateUris(List<CmsDetailPageInfo> detailPages) { List<CmsDetailPageInfo> result = new ArrayList<CmsDetailPageInfo>(); for (CmsDetailPageInfo page : detailPages) { CmsUUID structureId = page.getId(); try { String rootPath = OpenCms.getADEManager().getRootPath( structureId, m_cms.getRequestContext().getCurrentProject().isOnlineProject()); CmsDetailPageInfo correctedPage = new CmsDetailPageInfo(structureId, rootPath, page.getType()); result.add(correctedPage); } catch (CmsException e) { LOG.warn(e.getLocalizedMessage(), e); } } return result; } }
package com.lucidworks.spark.fusion; import com.codahale.metrics.Meter; import com.codahale.metrics.MetricRegistry; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.http.HttpEntity; import org.apache.http.HttpException; import org.apache.http.HttpRequest; import org.apache.http.HttpRequestInterceptor; import org.apache.http.HttpResponse; import org.apache.http.auth.UsernamePasswordCredentials; import org.apache.http.client.CookieStore; import org.apache.http.client.HttpClient; import org.apache.http.client.config.CookieSpecs; import org.apache.http.client.config.RequestConfig; import org.apache.http.client.methods.HttpPost; import org.apache.http.client.methods.HttpUriRequest; import org.apache.http.client.protocol.HttpClientContext; import org.apache.http.cookie.Cookie; import org.apache.http.entity.ContentProducer; import org.apache.http.entity.ContentType; import org.apache.http.entity.EntityTemplate; import org.apache.http.entity.StringEntity; import org.apache.http.impl.auth.BasicScheme; import org.apache.http.impl.client.BasicCookieStore; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.impl.cookie.BasicClientCookie; import org.apache.http.protocol.HttpContext; import org.apache.http.util.EntityUtils; import org.apache.solr.client.solrj.impl.HttpClientUtil; import org.apache.solr.client.solrj.impl.Krb5HttpClientConfigurer; import org.apache.solr.common.SolrException; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.module.scala.DefaultScalaModule; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStream; import java.net.MalformedURLException; import java.net.URL; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.Arrays; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Random; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; public class FusionPipelineClient { private static final Log log = LogFactory.getLog(FusionPipelineClient.class); public static final String PIPELINE_DOC_CONTENT_TYPE = "application/vnd.lucidworks-document"; public static final String LWWW_JAAS_FILE = "lww.jaas.file"; public static final String LWWW_JAAS_APPNAME = "lww.jaas.appname"; public static void setSecurityConfig(String jassFile) { if (jassFile == null) return; log.info("Using kerberized Solr."); System.setProperty("sun.security.krb5.debug", "true"); System.setProperty("java.security.auth.login.config", jassFile); final String appname = System.getProperty(LWWW_JAAS_APPNAME, "Client"); System.setProperty("solr.kerberos.jaas.appname", appname); HttpClientUtil.setConfigurer(new Krb5HttpClientConfigurer()); } // for basic auth to the pipeline service private static final class PreEmptiveBasicAuthenticator implements HttpRequestInterceptor { private final UsernamePasswordCredentials credentials; public PreEmptiveBasicAuthenticator(String user, String pass) { credentials = new UsernamePasswordCredentials(user, pass); } public void process(HttpRequest request, HttpContext context) throws HttpException, IOException { request.addHeader(BasicScheme.authenticate(credentials, "US-ASCII", false)); } } // holds a context and a client object static class FusionSession { String id; long sessionEstablishedAt = -1; Meter docsSentMeter = null; public String toString() { StringBuilder sb = new StringBuilder(); sb.append(id); if (sessionEstablishedAt > 0) { sb.append(": ").append(TimeUnit.SECONDS.convert(sessionEstablishedAt, TimeUnit.NANOSECONDS)); } if (docsSentMeter != null) { sb.append(", docsSent: ").append(docsSentMeter.getCount()); } return sb.toString(); } } List<String> originalHostAndPortList; RequestConfig globalConfig; CookieStore cookieStore; CloseableHttpClient httpClient; Map<String, FusionSession> sessions; Random random; ObjectMapper jsonObjectMapper; String fusionUser = null; String fusionPass = null; String fusionRealm = null; AtomicInteger requestCounter = null; Map<String, Meter> metersByHost = new HashMap<>(); boolean isKerberos = false; MetricRegistry metrics = null; static long maxNanosOfInactivity = TimeUnit.NANOSECONDS.convert(599, TimeUnit.SECONDS); public FusionPipelineClient(String fusionHostAndPortList) throws MalformedURLException { this(fusionHostAndPortList, null, null, null); } public FusionPipelineClient(String fusionHostAndPortList, String fusionUser, String fusionPass, String fusionRealm) throws MalformedURLException { this.fusionUser = fusionUser; this.fusionPass = fusionPass; this.fusionRealm = fusionRealm; String lwwJaasFile = System.getProperty(LWWW_JAAS_FILE); if (lwwJaasFile != null && !lwwJaasFile.isEmpty()) { setSecurityConfig(lwwJaasFile); httpClient = HttpClientUtil.createClient(null); HttpClientUtil.setMaxConnections(httpClient, 1000); HttpClientUtil.setMaxConnectionsPerHost(httpClient, 1000); isKerberos = true; } else { globalConfig = RequestConfig.custom().setCookieSpec(CookieSpecs.BEST_MATCH).build(); cookieStore = new BasicCookieStore(); // build the HttpClient to be used for all requests HttpClientBuilder httpClientBuilder = HttpClientBuilder.create(); httpClientBuilder.setDefaultRequestConfig(globalConfig).setDefaultCookieStore(cookieStore); httpClientBuilder.setMaxConnPerRoute(1000); httpClientBuilder.setMaxConnTotal(1000); if (fusionUser != null && fusionRealm == null) httpClientBuilder.addInterceptorFirst(new PreEmptiveBasicAuthenticator(fusionUser, fusionPass)); httpClient = httpClientBuilder.build(); } originalHostAndPortList = Arrays.asList(fusionHostAndPortList.split(",")); try { sessions = establishSessions(originalHostAndPortList, fusionUser, fusionPass, fusionRealm); } catch (Exception exc) { if (exc instanceof RuntimeException) { throw (RuntimeException) exc; } else { throw new RuntimeException(exc); } } random = new Random(); jsonObjectMapper = new ObjectMapper(); jsonObjectMapper.registerModule(new DefaultScalaModule()); requestCounter = new AtomicInteger(0); } public String getFusionUser() { return fusionUser; } public String getFusionRealm() { return fusionRealm; } public void setMetricsRegistry(MetricRegistry metrics) { this.metrics = metrics; } protected Meter getMeterByHost(String meterName, String host) { if (metrics == null) return null; String key = meterName + " (" + host + ")"; Meter meter = metersByHost.get(key); if (meter == null) { meter = metrics.meter(meterName + "-" + host); metersByHost.put(key, meter); } return meter; } protected Map<String, FusionSession> establishSessions(List<String> hostAndPortList, String user, String password, String realm) throws Exception { Exception lastError = null; Map<String, FusionSession> map = new HashMap<>(); for (String url : hostAndPortList) { String sessionKey = getSessionKey(url); if (!map.containsKey(sessionKey)) { try { FusionSession session = establishSession(sessionKey, user, password, realm); map.put(session.id, session); } catch (Exception exc) { // just log this ... so long as there is at least one good endpoint we can use it lastError = exc; log.warn("Failed to establish session with Fusion at " + sessionKey + " due to: " + exc); } } } if (map.isEmpty()) { if (lastError != null) { throw lastError; } else { throw new Exception("Failed to establish session with Fusion host(s): " + hostAndPortList); } } log.info("Established sessions with " + map.size() + " of " + hostAndPortList.size() + " Fusion hosts for user " + user + " in realm " + realm); return map; } protected FusionSession establishSession(String sessionKey, String user, String password, String realm) throws Exception { if (!sessionKey.startsWith("https: sessionKey = "http://" + sessionKey; } FusionSession fusionSession = new FusionSession(); if (!isKerberos && realm != null) { String sessionApi = sessionKey + "/api/session?realmName=" + realm; String jsonString = "{\"username\":\"" + user + "\", \"password\":\"" + password + "\"}"; URL sessionApiUrl = new URL(sessionApi); String sessionHost = sessionApiUrl.getHost(); try { clearCookieForHost(sessionHost); } catch (Exception exc) { log.warn("Failed to clear session cookie for " + sessionHost + " due to: " + exc); } HttpPost postRequest = new HttpPost(sessionApiUrl.toURI()); postRequest.setEntity(new StringEntity(jsonString, ContentType.create("application/json", StandardCharsets.UTF_8))); HttpClientContext context = HttpClientContext.create(); context.setCookieStore(cookieStore); HttpResponse response = httpClient.execute(postRequest, context); HttpEntity entity = response.getEntity(); try { int statusCode = response.getStatusLine().getStatusCode(); if (statusCode != 200 && statusCode != 201 && statusCode != 204) { String body = extractResponseBodyText(entity); throw new SolrException(SolrException.ErrorCode.getErrorCode(statusCode), "POST credentials to Fusion Session API [" + sessionApi + "] failed due to: " + response.getStatusLine() + ": " + body); } else if (statusCode == 401) { // retry in case this is an expired error String body = extractResponseBodyText(entity); if (body != null && body.indexOf("session-idle-timeout") != -1) { EntityUtils.consume(entity); // have to consume the previous entity before re-trying the request log.warn("Received session-idle-timeout error from Fusion Session API, re-trying to establish a new session to " + sessionKey); try { clearCookieForHost(sessionHost); } catch (Exception exc) { log.warn("Failed to clear session cookie for " + sessionHost + " due to: " + exc); } response = httpClient.execute(postRequest, context); entity = response.getEntity(); statusCode = response.getStatusLine().getStatusCode(); if (statusCode != 200 && statusCode != 201 && statusCode != 204) { body = extractResponseBodyText(entity); throw new SolrException(SolrException.ErrorCode.getErrorCode(statusCode), "POST credentials to Fusion Session API [" + sessionApi + "] failed due to: " + response.getStatusLine() + ": " + body); } } } } finally { if (entity != null) EntityUtils.consume(entity); } log.info("Established secure session with Fusion Session API on " + sessionKey + " for user " + user + " in realm " + realm); } fusionSession.sessionEstablishedAt = System.nanoTime(); fusionSession.docsSentMeter = getMeterByHost("Docs Sent to Fusion", sessionKey); fusionSession.id = sessionKey; return fusionSession; } protected synchronized void clearCookieForHost(String sessionHost) throws Exception { Cookie sessionCookie = null; for (Cookie cookie : cookieStore.getCookies()) { String cookieDomain = cookie.getDomain(); if (cookieDomain != null) { if (sessionHost.equals(cookieDomain) || sessionHost.indexOf(cookieDomain) != -1 || cookieDomain.indexOf(sessionHost) != -1) { sessionCookie = cookie; break; } } } if (sessionCookie != null) { BasicClientCookie httpCookie = new BasicClientCookie(sessionCookie.getName(), sessionCookie.getValue()); httpCookie.setExpiryDate(new Date(0)); httpCookie.setVersion(1); httpCookie.setPath(sessionCookie.getPath()); httpCookie.setDomain(sessionCookie.getDomain()); cookieStore.addCookie(httpCookie); } cookieStore.clearExpired(new Date()); // this should clear the cookie } protected String getSessionKey(String url) throws Exception { if (!url.startsWith("http: url = "http://"+url; URL javaUrl = new URL(url); return javaUrl.getProtocol() + "://" + javaUrl.getHost() + ":" + javaUrl.getPort(); } protected FusionSession getSession(String url, int requestId) throws Exception { String sessionKey = getSessionKey(url); FusionSession fusionSession; synchronized (this) { fusionSession = sessions.get(sessionKey); // ensure last request within the session timeout period, else reset the session long currTime = System.nanoTime(); if (fusionSession == null || (currTime - fusionSession.sessionEstablishedAt) > maxNanosOfInactivity) { log.info("Fusion session is likely expired (or soon will be) for " + url + ", " + "pre-emptively re-setting this session before processing request " + requestId); fusionSession = resetSession(sessionKey); if (fusionSession == null) throw new IllegalStateException("Failed to re-connect to " + url + " after session loss when processing request " + requestId); } } return fusionSession; } protected synchronized FusionSession resetSession(String sessionKey) throws Exception { // reset the "context" object for the HttpContext for this endpoint FusionSession fusionSession; try { fusionSession = establishSession(sessionKey, fusionUser, fusionPass, fusionRealm); sessions.put(fusionSession.id, fusionSession); } catch (Exception exc) { log.error("Failed to re-establish session with Fusion at " + sessionKey + " due to: " + exc); sessions.remove(sessionKey); fusionSession = null; } return fusionSession; } public HttpClient getHttpClient() { return httpClient; } public String getAvailableServer() { try { return getLbServer(getAvailableServers()); } catch (Exception exc) { if (exc instanceof RuntimeException) { throw (RuntimeException)exc; } else { throw new RuntimeException(exc); } } } protected String getLbServer(List<String> list) { int num = list.size(); if (num == 0) return null; return list.get((num > 1) ? random.nextInt(num) : 0); } public ArrayList<String> getAvailableServers() throws Exception { ArrayList<String> mutable; synchronized (this) { mutable = new ArrayList<>(sessions.keySet()); } if (mutable.isEmpty()) { // completely hosed ... try to re-establish all sessions synchronized (this) { try { Thread.sleep(2000); } catch (InterruptedException ie) { Thread.interrupted(); } sessions = establishSessions(originalHostAndPortList, fusionUser, fusionPass, fusionRealm); mutable = new ArrayList<>(sessions.keySet()); } if (mutable.isEmpty()) throw new IllegalStateException("No available endpoints! " + "Check log for previous errors as to why there are no more endpoints available. This is a fatal error."); } return mutable; } public void postBatchToPipeline(String pipelinePath, List docs) throws Exception { int numDocs = docs.size(); if (!pipelinePath.startsWith("/")) pipelinePath = "/" + pipelinePath; int requestId = requestCounter.incrementAndGet(); ArrayList<String> mutable = getAvailableServers(); if (mutable.size() > 1) { Exception lastExc = null; // try all the endpoints until success is reached ... or we run out of endpoints to try ... while (!mutable.isEmpty()) { String hostAndPort = getLbServer(mutable); if (hostAndPort == null) { // no more endpoints available ... fail if (lastExc != null) { log.error("No more hosts available to retry failed request (" + requestId + ")! raising last seen error: " + lastExc); throw lastExc; } else { throw new RuntimeException("No Fusion hosts available to process request " + requestId + "! Check logs for previous errors."); } } if (log.isDebugEnabled()) log.debug("POSTing batch of " + numDocs + " input docs to " + hostAndPort + pipelinePath + " as request " + requestId); Exception retryAfterException = postJsonToPipelineWithRetry(hostAndPort, pipelinePath, docs, mutable, lastExc, requestId); if (retryAfterException == null) { lastExc = null; break; // request succeeded ... } lastExc = retryAfterException; // try next hostAndPort (if available) after seeing an exception } if (lastExc != null) { // request failed and we exhausted the list of endpoints to try ... log.error("Failing request " + requestId + " due to: " + lastExc); throw lastExc; } } else { String hostAndPort = getLbServer(mutable); if (log.isDebugEnabled()) log.debug("POSTing batch of " + numDocs + " input docs to " + hostAndPort + pipelinePath + " as request " + requestId); Exception exc = postJsonToPipelineWithRetry(hostAndPort, pipelinePath, docs, mutable, null, requestId); if (exc != null) throw exc; } } protected Exception postJsonToPipelineWithRetry(String hostAndPort, String pipelinePath, List docs, ArrayList<String> mutable, Exception lastExc, int requestId) throws Exception { String url = hostAndPort + pipelinePath; Exception retryAfterException = null; try { postJsonToPipeline(hostAndPort, pipelinePath, docs, requestId); if (lastExc != null) log.info("Re-try request " + requestId + " to " + url + " succeeded after seeing a " + lastExc.getMessage()); } catch (Exception exc) { log.warn("Failed to send request " + requestId + " to '" + url + "' due to: " + exc); if (mutable.size() > 1) { // try another hostAndPort but update the cloned list to avoid re-hitting the one having an error if (log.isDebugEnabled()) log.debug("Will re-try failed request " + requestId + " on next host in the list"); mutable.remove(hostAndPort); retryAfterException = exc; } else { // no other endpoints to try ... brief wait and then retry log.warn("No more Fusion servers available to try ... will retry to send request " + requestId + " to " + url + " after waiting 1 sec"); try { Thread.sleep(1000); } catch (InterruptedException ignore) { Thread.interrupted(); } // note we want the exception to propagate from here up the stack since we re-tried and it didn't work postJsonToPipeline(hostAndPort, pipelinePath, docs, requestId); log.info("Re-try request " + requestId + " to " + url + " succeeded"); retryAfterException = null; // return success condition } } return retryAfterException; } private class JacksonContentProducer implements ContentProducer { ObjectMapper mapper; Object jsonObj; JacksonContentProducer(ObjectMapper mapper, Object jsonObj) { this.mapper = mapper; this.jsonObj = jsonObj; } public void writeTo(OutputStream outputStream) throws IOException { mapper.writeValue(outputStream, jsonObj); } } public void postJsonToPipeline(String hostAndPort, String pipelinePath, List docs, int requestId) throws Exception { FusionSession fusionSession = getSession(hostAndPort, requestId); String postUrl = hostAndPort + pipelinePath; if (postUrl.indexOf("?") != -1) { postUrl += "&echo=false"; } else { postUrl += "?echo=false"; } HttpPost postRequest = new HttpPost(postUrl); EntityTemplate et = new EntityTemplate(new JacksonContentProducer(jsonObjectMapper, docs)); et.setContentType(PIPELINE_DOC_CONTENT_TYPE); et.setContentEncoding(StandardCharsets.UTF_8.name()); postRequest.setEntity(et); HttpEntity entity = null; try { HttpResponse response; HttpClientContext context = null; if (isKerberos) { response = httpClient.execute(postRequest); } else { context = HttpClientContext.create(); if (cookieStore != null) { context.setCookieStore(cookieStore); } response = httpClient.execute(postRequest, context); } entity = response.getEntity(); int statusCode = response.getStatusLine().getStatusCode(); if (statusCode == 401) { // unauth'd - session probably expired? retry to establish log.warn("Unauthorized error (401) when trying to send request " + requestId + " to Fusion at " + hostAndPort + ", will re-try to establish session"); // re-establish the session and re-try the request try { EntityUtils.consume(entity); } catch (Exception ignore) { log.warn("Failed to consume entity due to: " + ignore); } finally { entity = null; } synchronized (this) { fusionSession = resetSession(hostAndPort); if (fusionSession == null) throw new IllegalStateException("After re-establishing session when processing request " + requestId + ", hostAndPort " + hostAndPort + " is no longer active! Try another hostAndPort."); } log.info("Going to re-try request " + requestId + " after session re-established with " + hostAndPort); if (isKerberos) { response = httpClient.execute(postRequest); } else { response = httpClient.execute(postRequest, context); } entity = response.getEntity(); statusCode = response.getStatusLine().getStatusCode(); if (statusCode == 200 || statusCode == 204) { log.info("Re-try request " + requestId + " after session timeout succeeded for: " + hostAndPort); } else { raiseFusionServerException(hostAndPort, entity, statusCode, response, requestId); } } else if (statusCode != 200 && statusCode != 204) { raiseFusionServerException(hostAndPort, entity, statusCode, response, requestId); } else { if (fusionSession != null && fusionSession.docsSentMeter != null) fusionSession.docsSentMeter.mark(docs.size()); } } finally { if (entity != null) { try { EntityUtils.consume(entity); } catch (Exception ignore) { log.warn("Failed to consume entity due to: " + ignore); } } } } public HttpEntity sendRequestToFusion(HttpUriRequest httpRequest) throws Exception { return sendRequestToFusion(httpRequest, true); } public HttpEntity sendRequestToFusion(HttpUriRequest httpRequest, boolean retry) throws Exception { String endpoint = httpRequest.getRequestLine().getUri(); int requestId = requestCounter.incrementAndGet(); FusionSession fusionSession = getSession(endpoint, requestId); HttpEntity entity; HttpResponse response; HttpClientContext context = null; if (log.isDebugEnabled()) { log.debug("Sending "+httpRequest.getMethod()+" request to: "+endpoint); } if (isKerberos) { response = httpClient.execute(httpRequest); } else { context = HttpClientContext.create(); if (cookieStore != null) { context.setCookieStore(cookieStore); } response = httpClient.execute(httpRequest, context); } entity = response.getEntity(); int statusCode = response.getStatusLine().getStatusCode(); if (log.isDebugEnabled()) { log.debug(httpRequest.getMethod()+" request to "+endpoint+" returned: "+statusCode); } if (!retry) { if (statusCode == 200 || statusCode == 204) { return entity; } else { raiseFusionServerException(endpoint, entity, statusCode, response, requestId); } } if (statusCode == 401) { // unauth'd - session probably expired? retry to establish log.warn("Unauthorized error (401) when trying to send request " + requestId + " to Fusion at " + endpoint + ", will re-try to establish session"); // re-establish the session and re-try the request try { EntityUtils.consume(entity); } catch (Exception ignore) { log.warn("Failed to consume entity due to: " + ignore); } finally { entity = null; } String sessionKey = fusionSession.id; synchronized (this) { fusionSession = resetSession(sessionKey); if (fusionSession == null) throw new IllegalStateException("After re-establishing session when processing request " + requestId + ", Fusion host " + sessionKey + " is no longer active! Try another server."); } log.info("Going to re-try request " + requestId + " after session re-established with " + sessionKey); if (isKerberos) { response = httpClient.execute(httpRequest); } else { response = httpClient.execute(httpRequest, context); } entity = response.getEntity(); statusCode = response.getStatusLine().getStatusCode(); if (statusCode == 200 || statusCode == 204) { log.info("Re-try request " + requestId + " after session timeout succeeded for: " + endpoint); } else { raiseFusionServerException(endpoint, entity, statusCode, response, requestId); } } else if (statusCode != 200 && statusCode != 204) { raiseFusionServerException(endpoint, entity, statusCode, response, requestId); } return entity; } protected void raiseFusionServerException(String endpoint, HttpEntity entity, int statusCode, HttpResponse response, int requestId) { String body = extractResponseBodyText(entity); throw new SolrException(SolrException.ErrorCode.getErrorCode(statusCode), "Request " + requestId + " to [" + endpoint + "] failed due to: (" + statusCode + ")" + response.getStatusLine() + ": " + body); } public static String extractResponseBodyText(HttpEntity entity) { StringBuilder body = new StringBuilder(); if (entity != null) { BufferedReader reader = null; String line = null; try { reader = new BufferedReader(new InputStreamReader(entity.getContent())); while ((line = reader.readLine()) != null) body.append(line); } catch (Exception ignore) { // squelch it - just trying to compose an error message here log.warn("Failed to read response body due to: " + ignore); } finally { if (reader != null) { try { reader.close(); } catch (Exception ignore) { } } } } return body.toString(); } public synchronized void shutdown() { if (sessions != null) { sessions.clear(); sessions = null; } if (httpClient != null) { try { httpClient.close(); } catch (IOException e) { log.warn("Failed to close httpClient object due to: " + e); } finally { httpClient = null; } } else { log.error("Already shutdown."); } } }
package dr.evomodel.beagle.treelikelihood; import dr.evolution.alignment.PatternList; import dr.evolution.tree.NodeRef; import dr.evolution.tree.Tree; import dr.evolution.util.TaxonList; import dr.evomodel.branchratemodel.BranchRateModel; import dr.evomodel.branchratemodel.DefaultBranchRateModel; import dr.evomodel.sitemodel.SiteModel; import dr.evomodel.substmodel.FrequencyModel; import dr.evomodel.substmodel.SubstitutionModel; import dr.evomodel.tree.TreeModel; import dr.evomodel.beagle.parsers.TreeLikelihoodParser; import dr.evomodel.beagle.sitemodel.SiteRateModel; import dr.evomodel.beagle.sitemodel.BranchSiteModel; import dr.evomodel.beagle.substmodel.EigenDecomposition; import dr.inference.model.Model; import java.util.logging.Logger; import java.util.Map; import java.util.HashMap; import beagle.BeagleFactory; import beagle.Beagle; /** * TreeLikelihoodModel - implements a Likelihood Function for sequences on a tree. * * @author Andrew Rambaut * @author Alexei Drummond * @version $Id: TreeLikelihood.java,v 1.31 2006/08/30 16:02:42 rambaut Exp $ */ public class BeagleTreeLikelihood extends AbstractTreeLikelihood { /** * Constructor. */ public BeagleTreeLikelihood(PatternList patternList, TreeModel treeModel, BranchSiteModel branchSiteModel, SiteRateModel siteRateModel, BranchRateModel branchRateModel, boolean useAmbiguities, int deviceNumber ) { super(TreeLikelihoodParser.TREE_LIKELIHOOD, patternList, treeModel); try { final Logger logger = Logger.getLogger("dr.evomodel"); logger.info("Using BEAGLE TreeLikelihood"); this.siteRateModel = siteRateModel; addModel(this.siteRateModel); this.branchSiteModel = branchSiteModel; addModel(branchSiteModel); if (branchRateModel != null) { this.branchRateModel = branchRateModel; logger.info("Branch rate model used: " + branchRateModel.getModelName()); } else { this.branchRateModel = new DefaultBranchRateModel(); } addModel(this.branchRateModel); this.categoryCount = this.siteRateModel.getCategoryCount(); int extNodeCount = treeModel.getExternalNodeCount(); Map<String, Object> configuration = new HashMap<String, Object>(); configuration.put(BeagleFactory.STATE_COUNT, stateCount); configuration.put(BeagleFactory.SINGLE_PRECISION, false); configuration.put(BeagleFactory.INSTANCE_NUMBER, deviceNumber); beagle = BeagleFactory.loadBeagleInstance(configuration); // override use preference on useAmbiguities based on actual ability of the likelihood core if (!beagle.canHandleTipPartials()) { useAmbiguities = false; } if (!beagle.canHandleTipStates()){ useAmbiguities = true; } // dynamicRescaling = likelihoodCore.canHandleDynamicRescaling(); beagle.initialize( nodeCount, extNodeCount, patternCount, categoryCount, 1 // matrixCount ); for (int i = 0; i < extNodeCount; i++) { // Find the id of tip i in the patternList String id = treeModel.getTaxonId(i); int index = patternList.getTaxonIndex(id); if (index == -1) { throw new TaxonList.MissingTaxonException("Taxon, " + id + ", in tree, " + treeModel.getId() + ", is not found in patternList, " + patternList.getId()); } else { if (useAmbiguities) { setPartials(beagle, patternList, index, i); } else { setStates(beagle, patternList, index, i); } } } updateSubstitutionModel = true; updateSiteModel = true; } catch (TaxonList.MissingTaxonException mte) { throw new RuntimeException(mte.toString()); } hasInitialized = true; } /** * Sets the partials from a sequence in an alignment. */ protected final void setPartials(Beagle beagle, PatternList patternList, int sequenceIndex, int nodeIndex) { double[] partials = new double[patternCount * stateCount]; boolean[] stateSet; int v = 0; for (int i = 0; i < patternCount; i++) { int state = patternList.getPatternState(sequenceIndex, i); stateSet = dataType.getStateSet(state); for (int j = 0; j < stateCount; j++) { if (stateSet[j]) { partials[v] = 1.0; } else { partials[v] = 0.0; } v++; } } beagle.setTipPartials(nodeIndex, partials); } /** * Sets the partials from a sequence in an alignment. */ protected final void setStates(Beagle beagle, PatternList patternList, int sequenceIndex, int nodeIndex) { int i; int[] states = new int[patternCount]; for (i = 0; i < patternCount; i++) { states[i] = patternList.getPatternState(sequenceIndex, i); } beagle.setTipStates(nodeIndex, states); } // ModelListener IMPLEMENTATION /** * Handles model changed events from the submodels. */ protected void handleModelChangedEvent(Model model, Object object, int index) { if (model == treeModel) { if (object instanceof TreeModel.TreeChangedEvent) { if (((TreeModel.TreeChangedEvent) object).isNodeChanged()) { // If a node event occurs the node and its two child nodes // are flagged for updating (this will result in everything // above being updated as well. Node events occur when a node // is added to a branch, removed from a branch or its height or // rate changes. updateNodeAndChildren(((TreeModel.TreeChangedEvent) object).getNode()); } else if (((TreeModel.TreeChangedEvent) object).isTreeChanged()) { // Full tree events result in a complete updating of the tree likelihood // Currently this event type is not used. System.err.println("Full tree update event - these events currently aren't used\n" + "so either this is in error or a new feature is using them so remove this message."); updateAllNodes(); } else { // Other event types are ignored (probably trait changes). //System.err.println("Another tree event has occured (possibly a trait change)."); } } } else if (model == branchRateModel) { if (index == -1) { updateAllNodes(); } else { updateNode(treeModel.getNode(index)); } } else if (model == branchSiteModel) { updateSubstitutionModel = true; updateAllNodes(); } else if (model == siteRateModel) { updateSubstitutionModel = true; updateSiteModel = true; updateAllNodes(); } else { throw new RuntimeException("Unknown componentChangedEvent"); } super.handleModelChangedEvent(model, object, index); } // Model IMPLEMENTATION /** * Stores the additional state other than model components */ protected void storeState() { beagle.storeState(); super.storeState(); } /** * Restore the additional stored state */ protected void restoreState() { beagle.restoreState(); super.restoreState(); } // Likelihood IMPLEMENTATION /** * Calculate the log likelihood of the current state. * * @return the log likelihood. */ protected double calculateLogLikelihood() { if (patternLogLikelihoods == null) { patternLogLikelihoods = new double[patternCount]; } if (branchUpdateIndices == null) { branchUpdateIndices = new int[nodeCount]; branchLengths = new double[nodeCount]; } if (operations == null) { operations = new int[nodeCount * 3]; dependencies = new int[nodeCount * 2]; } branchUpdateCount = 0; operationCount = 0; final NodeRef root = treeModel.getRoot(); traverse(treeModel, root, null); if (updateSubstitutionModel) { // we are currently assuming a homogenous model... EigenDecomposition ed = branchSiteModel.getEigenDecomposition(0, 0); beagle.setStateFrequencies(branchSiteModel.getStateFrequencies(0)); beagle.setEigenDecomposition( 0, // we are only dealing with a single matrix over all categories ed.getEigenVectors(), ed.getInverseEigenVectors(), ed.getEigenValues()); } if (updateSiteModel) { beagle.setCategoryRates(this.siteRateModel.getCategoryRates()); beagle.setCategoryProportions(this.siteRateModel.getCategoryProportions()); } beagle.calculateProbabilityTransitionMatrices(branchUpdateIndices, branchLengths, branchUpdateCount); beagle.calculatePartials(operations,dependencies, operationCount); nodeEvaluationCount += operationCount; beagle.calculateLogLikelihoods(root.getNumber(), patternLogLikelihoods); double logL = 0.0; for (int i = 0; i < patternCount; i++) { logL += patternLogLikelihoods[i] * patternWeights[i]; } // Attempt dynamic rescaling if over/under-flow if (logL == Double.NaN || logL == Double.POSITIVE_INFINITY ) { System.err.println("Potential under/over-flow; going to attempt a partials rescaling."); updateAllNodes(); branchUpdateCount = 0; operationCount = 0; traverse(treeModel, root, null); beagle.calculatePartials(operations,dependencies, operationCount); beagle.calculateLogLikelihoods(root.getNumber(), patternLogLikelihoods); logL = 0.0; for (int i = 0; i < patternCount; i++) { logL += patternLogLikelihoods[i] * patternWeights[i]; } } /** * Traverse the tree calculating partial likelihoods. */ private boolean traverse(Tree tree, NodeRef node, int[] operatorNumber) { boolean update = false; int nodeNum = node.getNumber(); NodeRef parent = tree.getParent(node); // First update the transition probability matrix(ices) for this branch if (parent != null && updateNode[nodeNum]) { final double branchRate = branchRateModel.getBranchRate(tree, node); // Get the operational time of the branch final double branchTime = branchRate * (tree.getNodeHeight(parent) - tree.getNodeHeight(node)); if (branchTime < 0.0) { throw new RuntimeException("Negative branch length: " + branchTime); } branchUpdateIndices[branchUpdateCount] = nodeNum; branchLengths[branchUpdateCount] = branchTime; branchUpdateCount++; update = true; } // If the node is internal, update the partial likelihoods. if (!tree.isExternal(node)) { // Traverse down the two child nodes NodeRef child1 = tree.getChild(node, 0); final int[] op1 = new int[] { -1 }; final boolean update1 = traverse(tree, child1, op1); NodeRef child2 = tree.getChild(node, 1); final int[] op2 = new int[] { -1 }; final boolean update2 = traverse(tree, child2, op2); // If either child node was updated then update this node too if (update1 || update2) { int x = operationCount * 3; operations[x] = child1.getNumber(); // source node 1 operations[x + 1] = child2.getNumber(); // source node 2 operations[x + 2] = nodeNum; // destination node int y = operationCount * 3; dependencies[y] = -1; // dependent ancestor dependencies[y + 1] = 0; // isDependent? // if one of the child nodes have an update then set the dependency // element to this operation. if (op1[0] != -1) { dependencies[op1[0] * 3] = operationCount; dependencies[y + 1] = 1; // isDependent? } if (op2[0] != -1) { dependencies[op2[0] * 3] = operationCount; dependencies[y + 1] = 1; // isDependent? } if (operatorNumber != null) { dependencies[y] = operationCount; } operationCount ++; update = true; } } return update; } // INSTANCE VARIABLES /** * the branch-site model for these sites */ protected final BranchSiteModel branchSiteModel; /** * the site model for these sites */ protected final SiteRateModel siteRateModel; /** * the branch rate model */ protected final BranchRateModel branchRateModel; /** * the pattern likelihoods */ protected double[] patternLogLikelihoods = null; /** * the number of rate categories */ protected int categoryCount; /** * an array used to transfer tip partials */ protected double[] tipPartials; /** * the BEAGLE library instance */ protected Beagle beagle; /** * Flag to specify that the substitution model has changed */ protected boolean updateSubstitutionModel; /** * Flag to specify that the site model has changed */ protected boolean updateSiteModel; private int nodeEvaluationCount = 0; public int getNodeEvaluationCount() { return nodeEvaluationCount; } // private boolean dynamicRescaling = false; }
package org.opencms.jsp.util; import org.opencms.ade.configuration.CmsADEConfigData; import org.opencms.ade.configuration.CmsADEManager; import org.opencms.ade.configuration.CmsFunctionReference; import org.opencms.ade.containerpage.CmsContainerpageService; import org.opencms.ade.containerpage.CmsModelGroupHelper; import org.opencms.ade.containerpage.shared.CmsFormatterConfig; import org.opencms.ade.containerpage.shared.CmsInheritanceInfo; import org.opencms.ade.detailpage.CmsDetailPageInfo; import org.opencms.ade.detailpage.CmsDetailPageResourceHandler; import org.opencms.file.CmsFile; import org.opencms.file.CmsObject; import org.opencms.file.CmsPropertyDefinition; import org.opencms.file.CmsRequestContext; import org.opencms.file.CmsResource; import org.opencms.file.CmsResourceFilter; import org.opencms.file.history.CmsHistoryResourceHandler; import org.opencms.flex.CmsFlexController; import org.opencms.flex.CmsFlexRequest; import org.opencms.gwt.shared.CmsGwtConstants; import org.opencms.i18n.CmsLocaleGroupService; import org.opencms.jsp.CmsJspBean; import org.opencms.jsp.CmsJspResourceWrapper; import org.opencms.jsp.CmsJspTagContainer; import org.opencms.jsp.CmsJspTagEditable; import org.opencms.jsp.Messages; import org.opencms.jsp.jsonpart.CmsJsonPartFilter; import org.opencms.loader.CmsTemplateContextManager; import org.opencms.main.CmsException; import org.opencms.main.CmsLog; import org.opencms.main.CmsRuntimeException; import org.opencms.main.CmsSystemInfo; import org.opencms.main.OpenCms; import org.opencms.relations.CmsCategory; import org.opencms.relations.CmsCategoryService; import org.opencms.site.CmsSite; import org.opencms.util.CmsCollectionsGenericWrapper; import org.opencms.util.CmsMacroResolver; import org.opencms.util.CmsStringUtil; import org.opencms.util.CmsUUID; import org.opencms.xml.containerpage.CmsADESessionCache; import org.opencms.xml.containerpage.CmsContainerBean; import org.opencms.xml.containerpage.CmsContainerElementBean; import org.opencms.xml.containerpage.CmsContainerPageBean; import org.opencms.xml.containerpage.CmsDynamicFunctionBean; import org.opencms.xml.containerpage.CmsDynamicFunctionParser; import org.opencms.xml.containerpage.CmsFormatterConfiguration; import org.opencms.xml.containerpage.CmsMetaMapping; import org.opencms.xml.containerpage.CmsXmlContainerPage; import org.opencms.xml.containerpage.CmsXmlContainerPageFactory; import org.opencms.xml.containerpage.I_CmsFormatterBean; import org.opencms.xml.content.CmsXmlContent; import org.opencms.xml.content.CmsXmlContentFactory; import org.opencms.xml.content.CmsXmlContentProperty; import org.opencms.xml.types.I_CmsXmlContentValue; import java.lang.reflect.Constructor; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Locale; import java.util.Map; import javax.servlet.ServletRequest; import javax.servlet.http.HttpServletRequest; import org.apache.commons.collections.Transformer; import org.apache.commons.lang3.LocaleUtils; import org.apache.commons.logging.Log; /** * Allows convenient access to the most important OpenCms functions on a JSP page, * indented to be used from a JSP with the JSTL or EL.<p> * * This bean is available by default in the context of an OpenCms managed JSP.<p> * * @since 8.0 */ public final class CmsJspStandardContextBean { /** * Container element wrapper to add some API methods.<p> */ public class CmsContainerElementWrapper extends CmsContainerElementBean { /** The wrapped element instance. */ private CmsContainerElementBean m_wrappedElement; /** * Constructor.<p> * * @param element the element to wrap */ protected CmsContainerElementWrapper(CmsContainerElementBean element) { m_wrappedElement = element; } /** * @see org.opencms.xml.containerpage.CmsContainerElementBean#clone() */ @Override public CmsContainerElementBean clone() { return m_wrappedElement.clone(); } /** * @see org.opencms.xml.containerpage.CmsContainerElementBean#editorHash() */ @Override public String editorHash() { return m_wrappedElement.editorHash(); } /** * @see org.opencms.xml.containerpage.CmsContainerElementBean#equals(java.lang.Object) */ @Override public boolean equals(Object obj) { return m_wrappedElement.equals(obj); } /** * @see org.opencms.xml.containerpage.CmsContainerElementBean#getFormatterId() */ @Override public CmsUUID getFormatterId() { return m_wrappedElement.getFormatterId(); } /** * @see org.opencms.xml.containerpage.CmsContainerElementBean#getId() */ @Override public CmsUUID getId() { return m_wrappedElement.getId(); } /** * @see org.opencms.xml.containerpage.CmsContainerElementBean#getIndividualSettings() */ @Override public Map<String, String> getIndividualSettings() { return m_wrappedElement.getIndividualSettings(); } /** * @see org.opencms.xml.containerpage.CmsContainerElementBean#getInheritanceInfo() */ @Override public CmsInheritanceInfo getInheritanceInfo() { return m_wrappedElement.getInheritanceInfo(); } /** * @see org.opencms.xml.containerpage.CmsContainerElementBean#getInstanceId() */ @Override public String getInstanceId() { return m_wrappedElement.getInstanceId(); } /** * Returns the parent element if present.<p> * * @return the parent element or <code>null</code> if not available */ public CmsContainerElementWrapper getParent() { CmsContainerElementBean parent = getParentElement(m_wrappedElement); return parent != null ? new CmsContainerElementWrapper(getParentElement(m_wrappedElement)) : null; } /** * @see org.opencms.xml.containerpage.CmsContainerElementBean#getResource() */ @Override public CmsResource getResource() { return m_wrappedElement.getResource(); } /** * Returns the resource type name of the element resource.<p> * * @return the resource type name */ public String getResourceTypeName() { String result = ""; try { result = OpenCms.getResourceManager().getResourceType(m_wrappedElement.getResource()).getTypeName(); } catch (Exception e) { CmsJspStandardContextBean.LOG.error(e.getLocalizedMessage(), e); } return result; } /** * Returns a lazy initialized setting map.<p> * * The values returned in the map are instances of {@link A_CmsJspValueWrapper}. * * @return the wrapped settings */ public Map<String, CmsJspElementSettingValueWrapper> getSetting() { return CmsCollectionsGenericWrapper.createLazyMap(new SettingsTransformer(m_wrappedElement)); } /** * @see org.opencms.xml.containerpage.CmsContainerElementBean#getSettings() */ @Override public Map<String, String> getSettings() { return m_wrappedElement.getSettings(); } /** * @see org.opencms.xml.containerpage.CmsContainerElementBean#getSitePath() */ @Override public String getSitePath() { return m_wrappedElement.getSitePath(); } /** * @see org.opencms.xml.containerpage.CmsContainerElementBean#hashCode() */ @Override public int hashCode() { return m_wrappedElement.hashCode(); } /** * @see org.opencms.xml.containerpage.CmsContainerElementBean#initResource(org.opencms.file.CmsObject) */ @Override public void initResource(CmsObject cms) throws CmsException { m_wrappedElement.initResource(cms); } /** * @see org.opencms.xml.containerpage.CmsContainerElementBean#initSettings(org.opencms.file.CmsObject, org.opencms.xml.containerpage.I_CmsFormatterBean, java.util.Locale, javax.servlet.ServletRequest) */ @Override public void initSettings( CmsObject cms, I_CmsFormatterBean formatterBean, Locale locale, ServletRequest request) { m_wrappedElement.initSettings(cms, formatterBean, locale, request); } /** * @see org.opencms.xml.containerpage.CmsContainerElementBean#isCreateNew() */ @Override public boolean isCreateNew() { return m_wrappedElement.isCreateNew(); } /** * @see org.opencms.xml.containerpage.CmsContainerElementBean#isGroupContainer(org.opencms.file.CmsObject) */ @Override public boolean isGroupContainer(CmsObject cms) throws CmsException { return m_wrappedElement.isGroupContainer(cms); } /** * @see org.opencms.xml.containerpage.CmsContainerElementBean#isInheritedContainer(org.opencms.file.CmsObject) */ @Override public boolean isInheritedContainer(CmsObject cms) throws CmsException { return m_wrappedElement.isInheritedContainer(cms); } /** * @see org.opencms.xml.containerpage.CmsContainerElementBean#isInMemoryOnly() */ @Override public boolean isInMemoryOnly() { return m_wrappedElement.isInMemoryOnly(); } /** * @see org.opencms.xml.containerpage.CmsContainerElementBean#isReleasedAndNotExpired() */ @Override public boolean isReleasedAndNotExpired() { return m_wrappedElement.isReleasedAndNotExpired(); } /** * @see org.opencms.xml.containerpage.CmsContainerElementBean#isTemporaryContent() */ @Override public boolean isTemporaryContent() { return m_wrappedElement.isTemporaryContent(); } /** * @see org.opencms.xml.containerpage.CmsContainerElementBean#removeInstanceId() */ @Override public void removeInstanceId() { m_wrappedElement.removeInstanceId(); } /** * @see org.opencms.xml.containerpage.CmsContainerElementBean#setFormatterId(org.opencms.util.CmsUUID) */ @Override public void setFormatterId(CmsUUID formatterId) { m_wrappedElement.setFormatterId(formatterId); } /** * @see org.opencms.xml.containerpage.CmsContainerElementBean#setHistoryFile(org.opencms.file.CmsFile) */ @Override public void setHistoryFile(CmsFile file) { m_wrappedElement.setHistoryFile(file); } /** * @see org.opencms.xml.containerpage.CmsContainerElementBean#setInheritanceInfo(org.opencms.ade.containerpage.shared.CmsInheritanceInfo) */ @Override public void setInheritanceInfo(CmsInheritanceInfo inheritanceInfo) { m_wrappedElement.setInheritanceInfo(inheritanceInfo); } /** * @see org.opencms.xml.containerpage.CmsContainerElementBean#setTemporaryFile(org.opencms.file.CmsFile) */ @Override public void setTemporaryFile(CmsFile elementFile) { m_wrappedElement.setTemporaryFile(elementFile); } /** * @see org.opencms.xml.containerpage.CmsContainerElementBean#toString() */ @Override public String toString() { return m_wrappedElement.toString(); } } /** * Provides a lazy initialized Map that provides the detail page link as a value when given the name of a * (named) dynamic function or resource type as a key.<p> */ public class CmsDetailLookupTransformer implements Transformer { /** The selected prefix. */ private String m_prefix; /** * Constructor with a prefix.<p> * * The prefix is used to distinguish between type detail pages and function detail pages.<p> * * @param prefix the prefix to use */ public CmsDetailLookupTransformer(String prefix) { m_prefix = prefix; } /** * @see org.apache.commons.collections.Transformer#transform(java.lang.Object) */ @Override public Object transform(Object input) { String type = m_prefix + String.valueOf(input); CmsADEConfigData config = OpenCms.getADEManager().lookupConfiguration( m_cms, m_cms.addSiteRoot(m_cms.getRequestContext().getUri())); List<CmsDetailPageInfo> detailPages = config.getDetailPagesForType(type); if ((detailPages == null) || (detailPages.size() == 0)) { return "[No detail page configured for type =" + type + "=]"; } CmsDetailPageInfo mainDetailPage = detailPages.get(0); CmsUUID id = mainDetailPage.getId(); try { CmsResource r = m_cms.readResource(id); return OpenCms.getLinkManager().substituteLink(m_cms, r); } catch (CmsException e) { LOG.warn(e.getLocalizedMessage(), e); return "[Error reading detail page for type =" + type + "=]"; } } } /** * The element setting transformer.<p> */ public class SettingsTransformer implements Transformer { /** The element formatter config. */ private I_CmsFormatterBean m_formatter; /** The element. */ private CmsContainerElementBean m_transformElement; /** The configured formatter settings. */ private Map<String, CmsXmlContentProperty> m_formatterSettingsConfig; /** * Constructor.<p> * * @param element the element */ SettingsTransformer(CmsContainerElementBean element) { m_transformElement = element; m_formatter = getElementFormatter(element); } /** * @see org.apache.commons.collections.Transformer#transform(java.lang.Object) */ @Override public Object transform(Object settingName) { boolean exists; if (m_formatter != null) { if (m_formatterSettingsConfig == null) { m_formatterSettingsConfig = OpenCms.getADEManager().getFormatterSettings( m_cms, m_formatter, m_transformElement.getResource(), getLocale(), m_request); } exists = m_formatterSettingsConfig.get(settingName) != null; } else { exists = m_transformElement.getSettings().get(settingName) != null; } return new CmsJspElementSettingValueWrapper( CmsJspStandardContextBean.this, m_transformElement.getSettings().get(settingName), exists); } } /** * Bean containing a template name and URI.<p> */ public static class TemplateBean { /** True if the template context was manually selected. */ private boolean m_forced; /** The template name. */ private String m_name; /** The template resource. */ private CmsResource m_resource; /** The template uri, if no resource is set. */ private String m_uri; /** * Creates a new instance.<p> * * @param name the template name * @param resource the template resource */ public TemplateBean(String name, CmsResource resource) { m_resource = resource; m_name = name; } /** * Creates a new instance with an URI instead of a resoure.<p> * * @param name the template name * @param uri the template uri */ public TemplateBean(String name, String uri) { m_name = name; m_uri = uri; } /** * Gets the template name.<p> * * @return the template name */ public String getName() { return m_name; } /** * Gets the template resource.<p> * * @return the template resource */ public CmsResource getResource() { return m_resource; } /** * Gets the template uri.<p> * * @return the template URI. */ public String getUri() { if (m_resource != null) { return m_resource.getRootPath(); } else { return m_uri; } } /** * Returns true if the template context was manually selected.<p> * * @return true if the template context was manually selected */ public boolean isForced() { return m_forced; } /** * Sets the 'forced' flag to a new value.<p> * * @param forced the new value */ public void setForced(boolean forced) { m_forced = forced; } } /** * The meta mappings transformer.<p> */ class MetaLookupTranformer implements Transformer { /** * @see org.apache.commons.collections.Transformer#transform(java.lang.Object) */ public Object transform(Object arg0) { String result = null; if (m_metaMappings.containsKey(arg0)) { MetaMapping mapping = m_metaMappings.get(arg0); try { CmsResourceFilter filter = getIsEditMode() ? CmsResourceFilter.IGNORE_EXPIRATION : CmsResourceFilter.DEFAULT; CmsResource res = m_cms.readResource(mapping.m_contentId, filter); CmsXmlContent content = CmsXmlContentFactory.unmarshal(m_cms, res, m_request); if (content.hasLocale(getLocale())) { I_CmsXmlContentValue val = content.getValue(mapping.m_elementXPath, getLocale()); if (val != null) { result = val.getStringValue(m_cms); } } } catch (CmsException e) { LOG.error(e.getLocalizedMessage(), e); } if (result == null) { result = mapping.m_defaultValue; } } return result; } } /** The meta mapping data. */ class MetaMapping { /** The mapping key. */ String m_key; /** The mapping value xpath. */ String m_elementXPath; /** The mapping order. */ int m_order; /** The mapping content structure id. */ CmsUUID m_contentId; /** The default value. */ String m_defaultValue; } /** The attribute name of the cms object.*/ public static final String ATTRIBUTE_CMS_OBJECT = "__cmsObject"; /** The attribute name of the standard JSP context bean. */ public static final String ATTRIBUTE_NAME = "cms"; /** The logger instance for this class. */ protected static final Log LOG = CmsLog.getLog(CmsJspStandardContextBean.class); /** OpenCms user context. */ protected CmsObject m_cms; /** Lazily initialized map from a category path to all sub-categories of that category. */ private Map<String, CmsJspCategoryAccessBean> m_allSubCategories; /** Lazily initialized map from a category path to the path's category object. */ private Map<String, CmsCategory> m_categories; /** The container the currently rendered element is part of. */ private CmsContainerBean m_container; /** The current detail content resource if available. */ private CmsResource m_detailContentResource; /** The detail only page references containers that are only displayed in detail view. */ private CmsContainerPageBean m_detailOnlyPage; /** Flag to indicate if element was just edited. */ private boolean m_edited; /** The currently rendered element. */ private CmsContainerElementBean m_element; /** The elements of the current page. */ private Map<String, CmsContainerElementBean> m_elementInstances; /** The lazy initialized map which allows access to the dynamic function beans. */ private Map<String, CmsDynamicFunctionBeanWrapper> m_function; /** The lazy initialized map for the function detail pages. */ private Map<String, String> m_functionDetailPage; /** Indicates if in drag mode. */ private boolean m_isDragMode; /** Stores the edit mode info. */ private Boolean m_isEditMode; /** Lazily initialized map from the locale to the localized title property. */ private Map<String, String> m_localeTitles; /** The currently displayed container page. */ private CmsContainerPageBean m_page; /** The current container page resource, lazy initialized. */ private CmsResource m_pageResource; /** The parent containers to the given element instance ids. */ private Map<String, CmsContainerBean> m_parentContainers; /** Lazily initialized map from a category path to all categories on that path. */ private Map<String, List<CmsCategory>> m_pathCategories; /** The current request. */ ServletRequest m_request; /** Lazily initialized map from the root path of a resource to all categories assigned to the resource. */ private Map<String, CmsJspCategoryAccessBean> m_resourceCategories; /** The resource wrapper for the current page. */ private CmsJspResourceWrapper m_resourceWrapper; /** The lazy initialized map for the detail pages. */ private Map<String, String> m_typeDetailPage; /** The VFS content access bean. */ private CmsJspVfsAccessBean m_vfsBean; /** The meta mapping configuration. */ Map<String, MetaMapping> m_metaMappings; /** Map from root paths to site relative paths. */ private Map<String, String> m_sitePaths; /** * Creates an empty instance.<p> */ private CmsJspStandardContextBean() { // NOOP } /** * Creates a new standard JSP context bean. * * @param req the current servlet request */ private CmsJspStandardContextBean(ServletRequest req) { CmsFlexController controller = CmsFlexController.getController(req); m_request = req; CmsObject cms; if (controller != null) { cms = controller.getCmsObject(); } else { cms = (CmsObject)req.getAttribute(ATTRIBUTE_CMS_OBJECT); } if (cms == null) { // cms object unavailable - this request was not initialized properly throw new CmsRuntimeException( Messages.get().container(Messages.ERR_MISSING_CMS_CONTROLLER_1, CmsJspBean.class.getName())); } updateCmsObject(cms); m_detailContentResource = CmsDetailPageResourceHandler.getDetailResource(req); } /** * Creates a new instance of the standard JSP context bean.<p> * * To prevent multiple creations of the bean during a request, the OpenCms request context * attributes are used to cache the created VFS access utility bean.<p> * * @param req the current servlet request * * @return a new instance of the standard JSP context bean */ public static CmsJspStandardContextBean getInstance(ServletRequest req) { Object attribute = req.getAttribute(ATTRIBUTE_NAME); CmsJspStandardContextBean result; if ((attribute != null) && (attribute instanceof CmsJspStandardContextBean)) { result = (CmsJspStandardContextBean)attribute; } else { result = new CmsJspStandardContextBean(req); req.setAttribute(ATTRIBUTE_NAME, result); } return result; } /** * Returns a copy of this JSP context bean.<p> * * @return a copy of this JSP context bean */ public CmsJspStandardContextBean createCopy() { CmsJspStandardContextBean result = new CmsJspStandardContextBean(); result.m_container = m_container; if (m_detailContentResource != null) { result.m_detailContentResource = m_detailContentResource.getCopy(); } result.m_element = m_element; result.setPage(m_page); return result; } /** * Returns a caching hash specific to the element, it's properties and the current container width.<p> * * @return the caching hash */ public String elementCachingHash() { String result = ""; if (m_element != null) { result = m_element.editorHash(); if (m_container != null) { result += "w:" + m_container.getWidth() + "cName:" + m_container.getName() + "cType:" + m_container.getType(); } } return result; } /** * Returns the locales available for the currently requested URI. * * @return the locales available for the currently requested URI. */ public List<Locale> getAvailableLocales() { return OpenCms.getLocaleManager().getAvailableLocales(m_cms, getRequestContext().getUri()); } /** * Helper for easy instantiation and initialization of custom context beans that returns * an instance of the class specified via <code>className</code>, with the current context already set. * * @param className name of the class to instantiate. Must be a subclass of {@link A_CmsJspCustomContextBean}. * @return an instance of the provided class with the current context already set. */ public Object getBean(String className) { try { Class<?> clazz = Class.forName(className); if (A_CmsJspCustomContextBean.class.isAssignableFrom(clazz)) { Constructor<?> constructor = clazz.getConstructor(); Object instance = constructor.newInstance(); Method setContextMethod = clazz.getMethod("setContext", CmsJspStandardContextBean.class); setContextMethod.invoke(instance, this); return instance; } else { throw new Exception(); } } catch (Exception e) { LOG.error(Messages.get().container(Messages.ERR_NO_CUSTOM_BEAN_1, className)); } return null; } /** * Returns the container the currently rendered element is part of.<p> * * @return the currently the currently rendered element is part of */ public CmsContainerBean getContainer() { return m_container; } /** * Returns the current detail content, or <code>null</code> if no detail content is requested.<p> * * @return the current detail content, or <code>null</code> if no detail content is requested.<p> */ public CmsResource getDetailContent() { return m_detailContentResource; } /** * Returns the structure id of the current detail content, or <code>null</code> if no detail content is requested.<p> * * @return the structure id of the current detail content, or <code>null</code> if no detail content is requested.<p> */ public CmsUUID getDetailContentId() { return m_detailContentResource == null ? null : m_detailContentResource.getStructureId(); } /** * Returns the detail content site path, or <code>null</code> if not available.<p> * * @return the detail content site path */ public String getDetailContentSitePath() { return ((m_cms == null) || (m_detailContentResource == null)) ? null : m_cms.getSitePath(m_detailContentResource); } /** * Returns the detail only page.<p> * * @return the detail only page */ public CmsContainerPageBean getDetailOnlyPage() { return m_detailOnlyPage; } /** * Returns the currently rendered element.<p> * * @return the currently rendered element */ public CmsContainerElementWrapper getElement() { return m_element != null ? new CmsContainerElementWrapper(m_element) : null; } /** * Alternative method name for getReloadMarker(). * * @see org.opencms.jsp.util.CmsJspStandardContextBean#getReloadMarker() * * @return the reload marker */ public String getEnableReload() { return getReloadMarker(); } /** * Returns a lazy initialized Map which allows access to the dynamic function beans using the JSP EL.<p> * * When given a key, the returned map will look up the corresponding dynamic function bean in the module configuration.<p> * * @return a lazy initialized Map which allows access to the dynamic function beans using the JSP EL */ public Map<String, CmsDynamicFunctionBeanWrapper> getFunction() { if (m_function == null) { Transformer transformer = new Transformer() { @Override public Object transform(Object input) { try { CmsDynamicFunctionBean dynamicFunction = readDynamicFunctionBean((String)input); CmsDynamicFunctionBeanWrapper wrapper = new CmsDynamicFunctionBeanWrapper( m_cms, dynamicFunction); return wrapper; } catch (CmsException e) { LOG.debug(e.getLocalizedMessage(), e); return new CmsDynamicFunctionBeanWrapper(m_cms, null); } } }; m_function = CmsCollectionsGenericWrapper.createLazyMap(transformer); } return m_function; } /** * Deprecated method to access function detail pages using the EL.<p> * * @return a lazy initialized Map that provides the detail page link as a value when given the name of a * (named) dynamic function as a key * * @deprecated use {@link #getFunctionDetailPage()} instead */ @Deprecated public Map<String, String> getFunctionDetail() { return getFunctionDetailPage(); } /** * Returns a lazy initialized Map that provides the detail page link as a value when given the name of a * (named) dynamic function as a key.<p> * * The provided Map key is assumed to be a String that represents a named dynamic function.<p> * * Usage example on a JSP with the JSTL:<pre> * &lt;a href=${cms.functionDetailPage['search']} /&gt * </pre> * * @return a lazy initialized Map that provides the detail page link as a value when given the name of a * (named) dynamic function as a key * * @see #getTypeDetailPage() */ public Map<String, String> getFunctionDetailPage() { if (m_functionDetailPage == null) { m_functionDetailPage = CmsCollectionsGenericWrapper.createLazyMap( new CmsDetailLookupTransformer(CmsDetailPageInfo.FUNCTION_PREFIX)); } return m_functionDetailPage; } /** * Returns a lazy map which creates a wrapper object for a dynamic function format when given an XML content * as a key.<p> * * @return a lazy map for accessing function formats for a content */ public Map<CmsJspContentAccessBean, CmsDynamicFunctionFormatWrapper> getFunctionFormatFromContent() { Transformer transformer = new Transformer() { @Override public Object transform(Object contentAccess) { CmsXmlContent content = (CmsXmlContent)(((CmsJspContentAccessBean)contentAccess).getRawContent()); CmsDynamicFunctionParser parser = new CmsDynamicFunctionParser(); CmsDynamicFunctionBean functionBean = null; try { functionBean = parser.parseFunctionBean(m_cms, content); } catch (CmsException e) { LOG.debug(e.getLocalizedMessage(), e); return new CmsDynamicFunctionFormatWrapper(m_cms, null); } String type = getContainer().getType(); String width = getContainer().getWidth(); int widthNum = -1; try { widthNum = Integer.parseInt(width); } catch (NumberFormatException e) { LOG.debug(e.getLocalizedMessage(), e); } CmsDynamicFunctionBean.Format format = functionBean.getFormatForContainer(m_cms, type, widthNum); CmsDynamicFunctionFormatWrapper wrapper = new CmsDynamicFunctionFormatWrapper(m_cms, format); return wrapper; } }; return CmsCollectionsGenericWrapper.createLazyMap(transformer); } /** * Checks if the current request should be direct edit enabled. * Online-, history-requests, previews and temporary files will not be editable.<p> * * @return <code>true</code> if the current request should be direct edit enabled */ public boolean getIsEditMode() { if (m_isEditMode == null) { m_isEditMode = Boolean.valueOf(CmsJspTagEditable.isEditableRequest(m_request)); } return m_isEditMode.booleanValue(); } /** * Returns true if the current request is a JSON request.<p> * * @return true if we are in a JSON request */ public boolean getIsJSONRequest() { return CmsJsonPartFilter.isJsonRequest(m_request); } /** * Returns if the current project is the online project.<p> * * @return <code>true</code> if the current project is the online project */ public boolean getIsOnlineProject() { return m_cms.getRequestContext().getCurrentProject().isOnlineProject(); } /** * Returns the current locale.<p> * * @return the current locale */ public Locale getLocale() { return getRequestContext().getLocale(); } /** * Gets a map providing access to the locale variants of the current page.<p> * * Note that all available locales for the site / subsite are used as keys, not just the ones for which a locale * variant actually exists. * * Usage in JSPs: ${cms.localeResource['de']] * * @return the map from locale strings to locale variant resources */ public Map<String, CmsJspResourceWrapper> getLocaleResource() { Map<String, CmsJspResourceWrapper> result = getResourceWrapperForPage().getLocaleResource(); List<Locale> locales = CmsLocaleGroupService.getPossibleLocales(m_cms, getContainerPage()); for (Locale locale : locales) { if (!result.containsKey(locale.toString())) { result.put(locale.toString(), null); } } return result; } /** * Gets the main locale for the current page's locale group.<p> * * @return the main locale for the current page's locale group */ public Locale getMainLocale() { return getResourceWrapperForPage().getMainLocale(); } /** * Returns the meta mappings map.<p> * * @return the meta mappings */ public Map<String, String> getMeta() { initMetaMappings(); return CmsCollectionsGenericWrapper.createLazyMap(new MetaLookupTranformer()); } /** * Returns the currently displayed container page.<p> * * @return the currently displayed container page */ public CmsContainerPageBean getPage() { return m_page; } /** * Returns the parent container to the current container if available.<p> * * @return the parent container */ public CmsContainerBean getParentContainer() { CmsContainerBean result = null; if ((getContainer() != null) && (getContainer().getParentInstanceId() != null)) { result = m_parentContainers.get(getContainer().getParentInstanceId()); } return result; } /** * Returns the instance id parent container mapping.<p> * * @return the instance id parent container mapping */ public Map<String, CmsContainerBean> getParentContainers() { if (m_parentContainers == null) { initPageData(); } return Collections.unmodifiableMap(m_parentContainers); } /** * Returns the parent element to the current element if available.<p> * * @return the parent element or null */ public CmsContainerElementBean getParentElement() { return getParentElement(getElement()); } /** * JSP EL accessor method for retrieving the preview formatters.<p> * * @return a lazy map for accessing preview formatters */ public Map<String, String> getPreviewFormatter() { Transformer transformer = new Transformer() { @Override public Object transform(Object uri) { try { String rootPath = m_cms.getRequestContext().addSiteRoot((String)uri); CmsResource resource = m_cms.readResource((String)uri); CmsADEManager adeManager = OpenCms.getADEManager(); CmsADEConfigData configData = adeManager.lookupConfiguration(m_cms, rootPath); CmsFormatterConfiguration formatterConfig = configData.getFormatters(m_cms, resource); if (formatterConfig == null) { return ""; } I_CmsFormatterBean previewFormatter = formatterConfig.getPreviewFormatter(); if (previewFormatter == null) { return ""; } CmsUUID structureId = previewFormatter.getJspStructureId(); m_cms.readResource(structureId); CmsResource formatterResource = m_cms.readResource(structureId); String formatterSitePath = m_cms.getRequestContext().removeSiteRoot( formatterResource.getRootPath()); return formatterSitePath; } catch (CmsException e) { LOG.warn(e.getLocalizedMessage(), e); return ""; } } }; return CmsCollectionsGenericWrapper.createLazyMap(transformer); } /** * Reads all sub-categories below the provided category. * @return The map from the provided category to it's sub-categories in a {@link CmsJspCategoryAccessBean}. */ public Map<String, CmsJspCategoryAccessBean> getReadAllSubCategories() { if (null == m_allSubCategories) { m_allSubCategories = CmsCollectionsGenericWrapper.createLazyMap(new Transformer() { @Override public Object transform(Object categoryPath) { try { List<CmsCategory> categories = CmsCategoryService.getInstance().readCategories( m_cms, (String)categoryPath, true, m_cms.getRequestContext().getUri()); CmsJspCategoryAccessBean result = new CmsJspCategoryAccessBean( m_cms, categories, (String)categoryPath); return result; } catch (CmsException e) { LOG.warn(e.getLocalizedMessage(), e); return null; } } }); } return m_allSubCategories; } /** * Reads the categories assigned to the currently requested URI. * @return the categories assigned to the currently requested URI. */ public CmsJspCategoryAccessBean getReadCategories() { return getReadResourceCategories().get(getRequestContext().getRootUri()); } /** * Transforms the category path of a category to the category. * @return a map from root or site path to category. */ public Map<String, CmsCategory> getReadCategory() { if (null == m_categories) { m_categories = CmsCollectionsGenericWrapper.createLazyMap(new Transformer() { public Object transform(Object categoryPath) { try { CmsCategoryService catService = CmsCategoryService.getInstance(); return catService.localizeCategory( m_cms, catService.readCategory(m_cms, (String)categoryPath, getRequestContext().getUri()), m_cms.getRequestContext().getLocale()); } catch (CmsException e) { LOG.warn(e.getLocalizedMessage(), e); return null; } } }); } return m_categories; } /** * Transforms the category path to the list of all categories on that path.<p> * * Example: For path <code>"location/europe/"</code> * the list <code>[getReadCategory.get("location/"),getReadCategory.get("location/europe/")]</code> * is returned. * @return a map from a category path to list of categories on that path. */ public Map<String, List<CmsCategory>> getReadPathCategories() { if (null == m_pathCategories) { m_pathCategories = CmsCollectionsGenericWrapper.createLazyMap(new Transformer() { public Object transform(Object categoryPath) { List<CmsCategory> result = new ArrayList<CmsCategory>(); String path = (String)categoryPath; if ((null == path) || (path.length() <= 1)) { return result; } //cut last slash path = path.substring(0, path.length() - 1); List<String> pathParts = Arrays.asList(path.split("/")); String currentPath = ""; for (String part : pathParts) { currentPath += part + "/"; CmsCategory category = getReadCategory().get(currentPath); if (null != category) { result.add(category); } } return CmsCategoryService.getInstance().localizeCategories( m_cms, result, m_cms.getRequestContext().getLocale()); } }); } return m_pathCategories; } /** * Reads the categories assigned to a resource. * * @return map from the resource path (root path) to the assigned categories */ public Map<String, CmsJspCategoryAccessBean> getReadResourceCategories() { if (null == m_resourceCategories) { m_resourceCategories = CmsCollectionsGenericWrapper.createLazyMap(new Transformer() { public Object transform(Object resourceName) { try { CmsResource resource = m_cms.readResource( getRequestContext().removeSiteRoot((String)resourceName)); return new CmsJspCategoryAccessBean(m_cms, resource); } catch (CmsException e) { LOG.warn(e.getLocalizedMessage(), e); return null; } } }); } return m_resourceCategories; } /** * Returns a HTML comment string that will cause the container page editor to reload the page if the element or its settings * were edited.<p> * * @return the reload marker */ public String getReloadMarker() { if (m_cms.getRequestContext().getCurrentProject().isOnlineProject()) { return ""; // reload marker is not needed in Online mode } else { return CmsGwtConstants.FORMATTER_RELOAD_MARKER; } } /** * Returns the request context.<p> * * @return the request context */ public CmsRequestContext getRequestContext() { return m_cms.getRequestContext(); } /** * Returns the current site.<p> * * @return the current site */ public CmsSite getSite() { return OpenCms.getSiteManager().getSiteForSiteRoot(m_cms.getRequestContext().getSiteRoot()); } /** * Transforms root paths to site paths. * * @return lazy map from root paths to site paths. * * @see CmsRequestContext#removeSiteRoot(String) */ public Map<String, String> getSitePath() { if (m_sitePaths == null) { m_sitePaths = CmsCollectionsGenericWrapper.createLazyMap(new Transformer() { public Object transform(Object rootPath) { if (rootPath instanceof String) { return getRequestContext().removeSiteRoot((String)rootPath); } return null; } }); } return m_sitePaths; } /** * Returns the subsite path for the currently requested URI.<p> * * @return the subsite path */ public String getSubSitePath() { return m_cms.getRequestContext().removeSiteRoot( OpenCms.getADEManager().getSubSiteRoot(m_cms, m_cms.getRequestContext().getRootUri())); } /** * Returns the system information.<p> * * @return the system information */ public CmsSystemInfo getSystemInfo() { return OpenCms.getSystemInfo(); } /** * Gets a bean containing information about the current template.<p> * * @return the template information bean */ public TemplateBean getTemplate() { TemplateBean templateBean = getRequestAttribute(CmsTemplateContextManager.ATTR_TEMPLATE_BEAN); if (templateBean == null) { templateBean = new TemplateBean("", ""); } return templateBean; } /** * Returns the title of a page delivered from OpenCms, usually used for the <code>&lt;title&gt;</code> tag of * a HTML page.<p> * * If no title information has been found, the empty String "" is returned.<p> * * @return the title of the current page */ public String getTitle() { return getLocaleSpecificTitle(null); } /** * Get the title and read the Title property according the provided locale. * @return The map from locales to the locale specific titles. */ public Map<String, String> getTitleLocale() { if (m_localeTitles == null) { m_localeTitles = CmsCollectionsGenericWrapper.createLazyMap(new Transformer() { public Object transform(Object inputLocale) { Locale locale = null; if (null != inputLocale) { if (inputLocale instanceof Locale) { locale = (Locale)inputLocale; } else if (inputLocale instanceof String) { try { locale = LocaleUtils.toLocale((String)inputLocale); } catch (IllegalArgumentException | NullPointerException e) { // do nothing, just go on without locale } } } return getLocaleSpecificTitle(locale); } }); } return m_localeTitles; } /** * Returns a lazy initialized Map that provides the detail page link as a value when given the name of a * resource type as a key.<p> * * The provided Map key is assumed to be the name of a resource type that has a detail page configured.<p> * * Usage example on a JSP with the JSTL:<pre> * &lt;a href=${cms.typeDetailPage['bs-blog']} /&gt * </pre> * * @return a lazy initialized Map that provides the detail page link as a value when given the name of a * resource type as a key * * @see #getFunctionDetailPage() */ public Map<String, String> getTypeDetailPage() { if (m_typeDetailPage == null) { m_typeDetailPage = CmsCollectionsGenericWrapper.createLazyMap(new CmsDetailLookupTransformer("")); } return m_typeDetailPage; } /** * Returns an initialized VFS access bean.<p> * * @return an initialized VFS access bean */ public CmsJspVfsAccessBean getVfs() { if (m_vfsBean == null) { // create a new VVFS access bean m_vfsBean = CmsJspVfsAccessBean.create(m_cms); } return m_vfsBean; } /** * Returns the workplace locale from the current user's settings.<p> * * @return returns the workplace locale from the current user's settings */ public Locale getWorkplaceLocale() { return OpenCms.getWorkplaceManager().getWorkplaceLocale(m_cms); } /** * Initializes the requested container page.<p> * * @param cms the cms context * @param req the current request * * @throws CmsException in case reading the requested resource fails */ public void initPage(CmsObject cms, HttpServletRequest req) throws CmsException { if (m_page == null) { String requestUri = cms.getRequestContext().getUri(); // get the container page itself, checking the history first CmsResource pageResource = (CmsResource)CmsHistoryResourceHandler.getHistoryResource(req); if (pageResource == null) { pageResource = cms.readResource(requestUri); } CmsXmlContainerPage xmlContainerPage = CmsXmlContainerPageFactory.unmarshal(cms, pageResource, req); m_page = xmlContainerPage.getContainerPage(cms); CmsModelGroupHelper modelHelper = new CmsModelGroupHelper( cms, OpenCms.getADEManager().lookupConfiguration(cms, cms.getRequestContext().getRootUri()), CmsJspTagEditable.isEditableRequest(req) ? CmsADESessionCache.getCache(req, cms) : null, CmsContainerpageService.isEditingModelGroups(cms, pageResource)); m_page = modelHelper.readModelGroups(xmlContainerPage.getContainerPage(cms)); } } /** * Returns <code>true</code in case a detail page is available for the current element.<p> * * @return <code>true</code in case a detail page is available for the current element */ public boolean isDetailPageAvailable() { boolean result = false; if ((m_cms != null) && (m_element != null) && !m_element.isInMemoryOnly() && (m_element.getResource() != null)) { try { String detailPage = OpenCms.getADEManager().getDetailPageFinder().getDetailPage( m_cms, m_element.getResource().getRootPath(), m_cms.getRequestContext().getUri(), null); result = detailPage != null; } catch (CmsException e) { LOG.warn(e.getLocalizedMessage(), e); } } return result; } /** * Returns <code>true</code> if this is a request to a detail resource, <code>false</code> otherwise.<p> * * Same as to check if {@link #getDetailContent()} is <code>null</code>.<p> * * @return <code>true</code> if this is a request to a detail resource, <code>false</code> otherwise */ public boolean isDetailRequest() { return m_detailContentResource != null; } /** * Returns if the page is in drag mode.<p> * * @return if the page is in drag mode */ public boolean isDragMode() { return m_isDragMode; } /** * Returns the flag to indicate if in drag and drop mode.<p> * * @return <code>true</code> if in drag and drop mode */ public boolean isEdited() { return m_edited; } /** * Returns if the current element is a model group.<p> * * @return <code>true</code> if the current element is a model group */ public boolean isModelGroupElement() { return (m_element != null) && !m_element.isInMemoryOnly() && isModelGroupPage() && m_element.isModelGroup(); } /** * Returns if the current page is used to manage model groups.<p> * * @return <code>true</code> if the current page is used to manage model groups */ public boolean isModelGroupPage() { CmsResource page = getContainerPage(); return (page != null) && CmsContainerpageService.isEditingModelGroups(m_cms, page); } /** * Sets the container the currently rendered element is part of.<p> * * @param container the container the currently rendered element is part of */ public void setContainer(CmsContainerBean container) { m_container = container; } /** * Sets the detail only page.<p> * * @param detailOnlyPage the detail only page to set */ public void setDetailOnlyPage(CmsContainerPageBean detailOnlyPage) { m_detailOnlyPage = detailOnlyPage; clearPageData(); } /** * Sets if the page is in drag mode.<p> * * @param isDragMode if the page is in drag mode */ public void setDragMode(boolean isDragMode) { m_isDragMode = isDragMode; } /** * Sets the flag to indicate if in drag and drop mode.<p> * * @param edited <code>true</code> if in drag and drop mode */ public void setEdited(boolean edited) { m_edited = edited; } /** * Sets the currently rendered element.<p> * * @param element the currently rendered element to set */ public void setElement(CmsContainerElementBean element) { m_element = element; } /** * Sets the currently displayed container page.<p> * * @param page the currently displayed container page to set */ public void setPage(CmsContainerPageBean page) { m_page = page; clearPageData(); } /** * Updates the internally stored OpenCms user context.<p> * * @param cms the new OpenCms user context */ public void updateCmsObject(CmsObject cms) { try { m_cms = OpenCms.initCmsObject(cms); } catch (CmsException e) { LOG.error(e.getLocalizedMessage(), e); m_cms = cms; } } /** * Updates the standard context bean from the request.<p> * * @param cmsFlexRequest the request from which to update the data */ public void updateRequestData(CmsFlexRequest cmsFlexRequest) { CmsResource detailRes = CmsDetailPageResourceHandler.getDetailResource(cmsFlexRequest); m_detailContentResource = detailRes; m_request = cmsFlexRequest; } /** * Returns the formatter configuration to the given element.<p> * * @param element the element * * @return the formatter configuration */ protected I_CmsFormatterBean getElementFormatter(CmsContainerElementBean element) { if (m_elementInstances == null) { initPageData(); } I_CmsFormatterBean formatter = null; CmsContainerBean container = m_parentContainers.get(element.getInstanceId()); if (container == null) { // use the current container container = getContainer(); } if (container != null) { String containerName = container.getName(); Map<String, String> settings = element.getSettings(); if (settings != null) { String formatterConfigId = settings.get(CmsFormatterConfig.getSettingsKeyForContainer(containerName)); if (CmsUUID.isValidUUID(formatterConfigId)) { formatter = OpenCms.getADEManager().getCachedFormatters(false).getFormatters().get( new CmsUUID(formatterConfigId)); } } if (formatter == null) { try { CmsResource resource = m_cms.readResource(m_cms.getRequestContext().getUri()); CmsADEConfigData config = OpenCms.getADEManager().lookupConfiguration( m_cms, resource.getRootPath()); CmsFormatterConfiguration formatters = config.getFormatters(m_cms, resource); int width = -2; try { width = Integer.parseInt(container.getWidth()); } catch (Exception e) { LOG.debug(e.getLocalizedMessage(), e); } formatter = formatters.getDefaultSchemaFormatter(container.getType(), width); } catch (CmsException e1) { LOG.error(e1.getLocalizedMessage(), e1); } } } return formatter; } /** * Returns the title according to the given locale. * @param locale the locale for which the title should be read. * @return the title according to the given locale */ protected String getLocaleSpecificTitle(Locale locale) { String result = null; try { if (isDetailRequest()) { // this is a request to a detail page CmsResource res = getDetailContent(); CmsFile file = m_cms.readFile(res); CmsXmlContent content = CmsXmlContentFactory.unmarshal(m_cms, file); result = content.getHandler().getTitleMapping(m_cms, content, m_cms.getRequestContext().getLocale()); if (result == null) { // title not found, maybe no mapping OR not available in the current locale // read the title of the detail resource as fall back (may contain mapping from another locale) result = m_cms.readPropertyObject( res, CmsPropertyDefinition.PROPERTY_TITLE, false, locale).getValue(); } } if (result == null) { // read the title of the requested resource as fall back result = m_cms.readPropertyObject( m_cms.getRequestContext().getUri(), CmsPropertyDefinition.PROPERTY_TITLE, true, locale).getValue(); } } catch (CmsException e) { LOG.debug(e.getLocalizedMessage(), e); } if (CmsStringUtil.isEmptyOrWhitespaceOnly(result)) { result = ""; } return result; } /** * Returns the parent element if available.<p> * * @param element the element * * @return the parent element or null */ protected CmsContainerElementBean getParentElement(CmsContainerElementBean element) { if (m_elementInstances == null) { initPageData(); } CmsContainerElementBean parent = null; CmsContainerBean cont = m_parentContainers.get(element.getInstanceId()); if ((cont != null) && cont.isNestedContainer()) { parent = m_elementInstances.get(cont.getParentInstanceId()); } return parent; } /** * Reads a dynamic function bean, given its name in the module configuration.<p> * * @param configuredName the name of the dynamic function in the module configuration * @return the dynamic function bean for the dynamic function configured under that name * * @throws CmsException if something goes wrong */ protected CmsDynamicFunctionBean readDynamicFunctionBean(String configuredName) throws CmsException { CmsADEConfigData config = OpenCms.getADEManager().lookupConfiguration( m_cms, m_cms.addSiteRoot(m_cms.getRequestContext().getUri())); CmsFunctionReference functionRef = config.getFunctionReference(configuredName); if (functionRef == null) { return null; } CmsDynamicFunctionParser parser = new CmsDynamicFunctionParser(); CmsResource functionResource = m_cms.readResource(functionRef.getStructureId()); CmsDynamicFunctionBean result = parser.parseFunctionBean(m_cms, functionResource); return result; } /** * Adds the mappings of the given formatter configuration.<p> * * @param formatterBean the formatter bean * @param elementId the element content structure id * @param resolver The macro resolver used on key and default value of the mappings * @param isDetailContent in case of a detail content */ private void addMappingsForFormatter( I_CmsFormatterBean formatterBean, CmsUUID elementId, CmsMacroResolver resolver, boolean isDetailContent) { if ((formatterBean != null) && (formatterBean.getMetaMappings() != null)) { for (CmsMetaMapping map : formatterBean.getMetaMappings()) { String key = map.getKey(); key = resolver.resolveMacros(key); // the detail content mapping overrides other mappings if (isDetailContent || !m_metaMappings.containsKey(key) || (m_metaMappings.get(key).m_order <= map.getOrder())) { MetaMapping mapping = new MetaMapping(); mapping.m_key = key; mapping.m_elementXPath = map.getElement(); mapping.m_defaultValue = resolver.resolveMacros(map.getDefaultValue()); mapping.m_order = map.getOrder(); mapping.m_contentId = elementId; m_metaMappings.put(key, mapping); } } } } /** * Clears the page element data.<p> */ private void clearPageData() { m_elementInstances = null; m_parentContainers = null; } /** * Returns the current container page resource.<p> * * @return the current container page resource */ private CmsResource getContainerPage() { try { if (m_pageResource == null) { // get the container page itself, checking the history first m_pageResource = (CmsResource)CmsHistoryResourceHandler.getHistoryResource(m_request); if (m_pageResource == null) { m_pageResource = m_cms.readResource(m_cms.getRequestContext().getUri()); } } } catch (CmsException e) { LOG.error(e.getLocalizedMessage(), e); } return m_pageResource; } /** * Convenience method for getting a request attribute without an explicit cast.<p> * * @param name the attribute name * @return the request attribute */ @SuppressWarnings("unchecked") private <A> A getRequestAttribute(String name) { Object attribute = m_request.getAttribute(name); return attribute != null ? (A)attribute : null; } /** * Gets the resource wrapper for the current page, initializing it if necessary.<p> * * @return the resource wrapper for the current page */ private CmsJspResourceWrapper getResourceWrapperForPage() { if (m_resourceWrapper != null) { return m_resourceWrapper; } m_resourceWrapper = new CmsJspResourceWrapper(m_cms, getContainerPage()); return m_resourceWrapper; } /** * Initializes the mapping configuration.<p> */ private void initMetaMappings() { if (m_metaMappings == null) { try { initPage(m_cms, (HttpServletRequest)m_request); CmsMacroResolver resolver = new CmsMacroResolver(); resolver.setCmsObject(m_cms); resolver.setMessages(OpenCms.getWorkplaceManager().getMessages(getLocale())); CmsResourceFilter filter = getIsEditMode() ? CmsResourceFilter.IGNORE_EXPIRATION : CmsResourceFilter.DEFAULT; m_metaMappings = new HashMap<String, MetaMapping>(); for (CmsContainerBean container : m_page.getContainers().values()) { for (CmsContainerElementBean element : container.getElements()) { String settingsKey = CmsFormatterConfig.getSettingsKeyForContainer(container.getName()); String formatterConfigId = element.getSettings() != null ? element.getSettings().get(settingsKey) : null; I_CmsFormatterBean formatterBean = null; if (CmsUUID.isValidUUID(formatterConfigId)) { formatterBean = OpenCms.getADEManager().getCachedFormatters( m_cms.getRequestContext().getCurrentProject().isOnlineProject()).getFormatters().get( new CmsUUID(formatterConfigId)); } if ((formatterBean != null) && m_cms.existsResource(element.getId(), filter)) { addMappingsForFormatter(formatterBean, element.getId(), resolver, false); } } } if (getDetailContentId() != null) { try { CmsResource detailContent = m_cms.readResource( getDetailContentId(), CmsResourceFilter.ignoreExpirationOffline(m_cms)); CmsFormatterConfiguration config = OpenCms.getADEManager().lookupConfiguration( m_cms, m_cms.getRequestContext().getRootUri()).getFormatters(m_cms, detailContent); for (I_CmsFormatterBean formatter : config.getDetailFormatters()) { addMappingsForFormatter(formatter, getDetailContentId(), resolver, true); } } catch (CmsException e) { LOG.error( Messages.get().getBundle().key( Messages.ERR_READING_REQUIRED_RESOURCE_1, getDetailContentId()), e); } } } catch (Exception e) { LOG.error(e.getLocalizedMessage(), e); } } } /** * Initializes the page element data.<p> */ private void initPageData() { m_elementInstances = new HashMap<String, CmsContainerElementBean>(); m_parentContainers = new HashMap<String, CmsContainerBean>(); if (m_page != null) { for (CmsContainerBean container : m_page.getContainers().values()) { for (CmsContainerElementBean element : container.getElements()) { m_elementInstances.put(element.getInstanceId(), element); m_parentContainers.put(element.getInstanceId(), container); try { if (element.isGroupContainer(m_cms) || element.isInheritedContainer(m_cms)) { List<CmsContainerElementBean> children; if (element.isGroupContainer(m_cms)) { children = CmsJspTagContainer.getGroupContainerElements( m_cms, element, m_request, container.getType()); } else { children = CmsJspTagContainer.getInheritedContainerElements(m_cms, element); } for (CmsContainerElementBean childElement : children) { m_elementInstances.put(childElement.getInstanceId(), childElement); m_parentContainers.put(childElement.getInstanceId(), container); } } } catch (CmsException e) { LOG.error(e.getLocalizedMessage(), e); } } } // also add detail only data if (m_detailOnlyPage != null) { for (CmsContainerBean container : m_detailOnlyPage.getContainers().values()) { for (CmsContainerElementBean element : container.getElements()) { m_elementInstances.put(element.getInstanceId(), element); m_parentContainers.put(element.getInstanceId(), container); } } } } } }
package dr.evomodel.branchratemodel; import dr.app.beagle.evomodel.substmodel.FrequencyModel; import dr.app.beagle.evomodel.substmodel.GeneralSubstitutionModel; import dr.app.beagle.evomodel.substmodel.SubstitutionModel; import dr.app.beagle.evomodel.substmodel.UniformizedSubstitutionModel; import dr.evolution.datatype.TwoStates; import dr.evolution.tree.NodeRef; import dr.evolution.tree.Tree; import dr.evolution.tree.TreeTrait; import dr.evomodel.tree.TreeModel; import dr.evomodel.tree.TreeParameterModel; import dr.inference.markovjumps.MarkovJumpsType; import dr.inference.model.AbstractModelLikelihood; import dr.inference.model.Model; import dr.inference.model.Parameter; import dr.inference.model.Variable; /** * LatentStateBranchRateModel * * @author Andrew Rambaut * @author Marc Suchard * @version $Id$ * * $HeadURL$ * * $LastChangedBy$ * $LastChangedDate$ * $LastChangedRevision$ */ public class LatentStateBranchRateModel extends AbstractModelLikelihood implements BranchRateModel { public static final String LATENT_STATE_BRANCH_RATE_MODEL = "latentStateBranchRateModel"; private final TreeModel tree; private final BranchRateModel nonLatentRateModel; private final Parameter latentTransitionRateParameter; private final Parameter latentStateProportionParameter; private final TreeParameterModel latentStateProportions; private UniformizedSubstitutionModel uSM = null; public LatentStateBranchRateModel(TreeModel treeModel, BranchRateModel nonLatentRateModel, Parameter latentTransitionRateParameter, Parameter latentStateProportionParameter) { this(LATENT_STATE_BRANCH_RATE_MODEL, treeModel, nonLatentRateModel, latentTransitionRateParameter, latentStateProportionParameter); } public LatentStateBranchRateModel(String name, TreeModel treeModel, BranchRateModel nonLatentRateModel, Parameter latentTransitionRateParameter, Parameter latentStateProportionParameter) { super(name); this.tree = treeModel; addModel(tree); this.nonLatentRateModel = nonLatentRateModel; addModel(nonLatentRateModel); this.latentTransitionRateParameter = latentTransitionRateParameter; addVariable(latentTransitionRateParameter); if (latentStateProportionParameter != null) { this.latentStateProportionParameter = latentStateProportionParameter; addVariable(latentTransitionRateParameter); } else { this.latentStateProportionParameter = new Parameter.Default(0.5); } this.latentStateProportions = new TreeParameterModel(tree, latentStateProportionParameter, false); } /** * Empty constructor for use by the main */ public LatentStateBranchRateModel() { super(LATENT_STATE_BRANCH_RATE_MODEL); tree = null; nonLatentRateModel = null; latentTransitionRateParameter = null; latentStateProportionParameter = null; latentStateProportions = null; } @Override public double getBranchRate(Tree tree, NodeRef node) { if (uSM == null) { createRewards(); } double length = tree.getBranchLength(node); double nonLatentRate = nonLatentRateModel.getBranchRate(tree, node); double latentProportion; if (latentStateProportionParameter != null) { latentProportion = latentStateProportions.getNodeValue(tree, node); } else { latentProportion = calculateLatentProportion(length); latentStateProportions.setNodeValue(tree, node, latentProportion); } return calculateBranchRate(nonLatentRate, latentProportion); } public double getLatentProportion(double length) { if (uSM == null) { createRewards(); } return calculateLatentProportion(length); } private double calculateLatentProportion(double length) { // Do this each time you need a new branch rate double reward = uSM.computeCondStatMarkovJumps(0, 0, length); double proportionTime = reward / length; return proportionTime; } private double calculateBranchRate(double nonLatentRate, double latentProportion) { return nonLatentRate * (1.0 - latentProportion); } private void createRewards() { FrequencyModel frequencyModel = new FrequencyModel(TwoStates.INSTANCE, new double[] { 0.5, 0.5 }); Parameter rateParameter = new Parameter.Default(new double[] { 1.0, 1.0 }); SubstitutionModel binaryModel = new GeneralSubstitutionModel("binary", TwoStates.INSTANCE, frequencyModel, rateParameter, 0); // Do this once, for all branches uSM = new UniformizedSubstitutionModel(binaryModel, MarkovJumpsType.REWARDS); uSM.setSaveCompleteHistory(true); double[] rewardRegister = new double[]{0.0, 1.0}; uSM.setRegistration(rewardRegister); } @Override protected void handleModelChangedEvent(Model model, Object object, int index) { if (model == tree) { } else if (model == nonLatentRateModel) { } } @Override protected void storeState() { } @Override protected void restoreState() { } @Override protected void acceptState() { } @Override protected void handleVariableChangedEvent(Variable variable, int index, Parameter.ChangeType type) { } @Override public Model getModel() { return this; } @Override public double getLogLikelihood() { throw new UnsupportedOperationException("Not implemented yet"); } @Override public void makeDirty() { } @Override public String getTraitName() { return null; } @Override public Intent getIntent() { return null; } @Override public Class getTraitClass() { return null; } @Override public Double getTrait(Tree tree, NodeRef node) { return null; } @Override public String getTraitString(Tree tree, NodeRef node) { return null; } @Override public boolean getLoggable() { return false; } @Override public TreeTrait[] getTreeTraits() { return new TreeTrait[0]; } @Override public TreeTrait getTreeTrait(String key) { return null; } public static void main(String[] args) { LatentStateBranchRateModel lsbrm = new LatentStateBranchRateModel(); double delta = 0.01; double[] values = new double[101]; int count = 100000; for (int i = 0; i < count; i++) { double length = 0.01; for (int j = 0; j < 100; j++) { values[j] += lsbrm.getLatentProportion(length); } } double length = 0.01; for (int j = 0; j < 100; j++) { System.out.println(length + "\t" + values[j] / count); length += delta; } } }
package org.opencms.ui.apps; import org.opencms.file.CmsObject; import org.opencms.file.CmsResource; import org.opencms.jsp.CmsJspTagEnableAde; import org.opencms.main.CmsException; import org.opencms.main.CmsLog; import org.opencms.main.OpenCms; import org.opencms.ui.A_CmsUI; import org.opencms.ui.CmsVaadinUtils; import org.opencms.ui.components.OpenCmsTheme; import org.opencms.util.CmsStringUtil; import java.util.Locale; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; import org.apache.commons.logging.Log; import com.vaadin.navigator.ViewChangeListener.ViewChangeEvent; import com.vaadin.server.ExternalResource; import com.vaadin.server.Resource; import com.vaadin.ui.Notification; import com.vaadin.ui.Notification.Type; /** * The page editor app configuration.<p> */ public class CmsPageEditorConfiguration extends A_CmsWorkplaceAppConfiguration implements I_CmsHasAppLaunchCommand { /** The app id. */ public static final String APP_ID = "pageeditor"; private static final Log LOG = CmsLog.getLog(CmsPageEditorConfiguration.class); /** * @see org.opencms.ui.apps.I_CmsWorkplaceAppConfiguration#getAppCategory() */ @Override public String getAppCategory() { return CmsWorkplaceAppManager.MAIN_CATEGORY_ID; } /** * @see org.opencms.ui.apps.I_CmsWorkplaceAppConfiguration#getAppInstance() */ public I_CmsWorkplaceApp getAppInstance() { throw new IllegalStateException("The editor app should be launched through the app launch command only."); } /** * @see org.opencms.ui.apps.I_CmsHasAppLaunchCommand#getAppLaunchCommand() */ public Runnable getAppLaunchCommand() { return new Runnable() { public void run() { openPageEditor(); } }; } /** * @see org.opencms.ui.apps.I_CmsWorkplaceAppConfiguration#getButtonStyle() */ @Override public String getButtonStyle() { return I_CmsAppButtonProvider.BUTTON_STYLE_TRANSPARENT; } /** * @see org.opencms.ui.apps.I_CmsWorkplaceAppConfiguration#getHelpText(java.util.Locale) */ @Override public String getHelpText(Locale locale) { return Messages.get().getBundle(locale).key(Messages.GUI_PAGEEDITOR_HELP_0); } /** * @see org.opencms.ui.apps.I_CmsWorkplaceAppConfiguration#getIcon() */ public Resource getIcon() { return new ExternalResource(OpenCmsTheme.getImageLink("apps/editor.png")); } /** * @see org.opencms.ui.apps.I_CmsWorkplaceAppConfiguration#getId() */ public String getId() { return APP_ID; } /** * @see org.opencms.ui.apps.I_CmsWorkplaceAppConfiguration#getName(java.util.Locale) */ @Override public String getName(Locale locale) { return Messages.get().getBundle(locale).key(Messages.GUI_PAGEEDITOR_TITLE_0); } /** * @see org.opencms.ui.apps.I_CmsWorkplaceAppConfiguration#getOrder() */ @Override public int getOrder() { return 1; } /** * @see org.opencms.ui.apps.I_CmsWorkplaceAppConfiguration#getVisibility(org.opencms.file.CmsObject) */ @Override public CmsAppVisibilityStatus getVisibility(CmsObject cms) { boolean active = !cms.getRequestContext().getCurrentProject().isOnlineProject() && CmsStringUtil.isNotEmptyOrWhitespaceOnly(cms.getRequestContext().getSiteRoot()); HttpServletRequest req = CmsVaadinUtils.getRequest(); String message = null; if (active) { if (req != null) { // this is a VAADIN UI request active = getPath(cms, req.getSession()) != null; if (!active) { message = CmsVaadinUtils.getMessageText(Messages.GUI_PAGE_EDITOR_PLEASE_SELECT_PAGE_0); } } } else { message = CmsVaadinUtils.getMessageText(Messages.GUI_PAGE_EDITOR_NOT_AVAILABLE_0); } return new CmsAppVisibilityStatus(true, active, message); } /** * Opens the page editor for the current site.<p> */ void openPageEditor() { CmsAppWorkplaceUi ui = CmsAppWorkplaceUi.get(); if (ui.beforeViewChange(new ViewChangeEvent(ui.getNavigator(), ui.getCurrentView(), null, APP_ID, null))) { CmsObject cms = A_CmsUI.getCmsObject(); HttpServletRequest req = CmsVaadinUtils.getRequest(); if (req == null) { // called from outside the VAADIN UI, not allowed throw new RuntimeException("Wrong usage, this can not be called from outside a VAADIN UI."); } CmsJspTagEnableAde.removeDirectEditFlagFromSession(req.getSession()); String page = getPath(cms, req.getSession()); if (page != null) { A_CmsUI.get().getPage().setLocation(OpenCms.getLinkManager().substituteLink(cms, page)); } else { String message = CmsVaadinUtils.getMessageText(Messages.GUI_PAGE_EDITOR_NOT_AVAILABLE_0); Notification.show(message, Type.WARNING_MESSAGE); } } } /** * Returns the page editor path to open.<p> * * @param cms the cms context * @param session the user session * * @return the path or <code>null</code> */ private String getPath(CmsObject cms, HttpSession session) { CmsQuickLaunchLocationCache locationCache = CmsQuickLaunchLocationCache.getLocationCache(session); String page = locationCache.getPageEditorLocation(cms.getRequestContext().getSiteRoot()); if (page == null) { try { CmsResource mainDefaultFile = cms.readDefaultFile("/"); if (mainDefaultFile != null) { page = cms.getSitePath(mainDefaultFile); } } catch (CmsException e) { LOG.error(e.getLocalizedMessage(), e); } } return page; } }
package cn.cerc.db.dao; import cn.cerc.db.core.ServerConfig; import cn.cerc.db.mysql.MysqlConnection; import com.mchange.v2.c3p0.ComboPooledDataSource; import lombok.extern.slf4j.Slf4j; import java.beans.PropertyVetoException; import java.io.Closeable; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; @Slf4j public class BigConnection implements Closeable { private static ComboPooledDataSource dataSource; /** * null null null * daoConnection */ private static ThreadLocal<Connection> connections = new ThreadLocal<Connection>(); private Connection connection; private boolean debugConnection = false; public BigConnection() { super(); connection = BigConnection.popConnection(); } public BigConnection(boolean debugConnection) { super(); this.debugConnection = debugConnection; if (!debugConnection) { connection = BigConnection.popConnection(); } } public synchronized static ComboPooledDataSource getDataSource() { if (dataSource == null) { ServerConfig config = ServerConfig.getInstance(); String host = config.getProperty(MysqlConnection.rds_site, "127.0.0.1:3306"); String database = config.getProperty(MysqlConnection.rds_database, "appdb"); String url = String.format("jdbc:mysql://%s/%s?useSSL=false&autoReconnect=true&autoCommit=false&useUnicode=true&characterEncoding=utf8&serverTimezone=Asia/Shanghai", host, database); String user = config.getProperty(MysqlConnection.rds_username, "appdb_user"); String pwd = config.getProperty(MysqlConnection.rds_password, "appdb_password"); int min_size = Integer.parseInt(config.getProperty("c3p0.min_size", "5")); int max_size = Integer.parseInt(config.getProperty("c3p0.max_size", "100")); int time_out = Integer.parseInt(config.getProperty("c3p0.time_out", "1800")); int max_statement = Integer.parseInt(config.getProperty("c3p0.max_statement", "100")); dataSource = new ComboPooledDataSource(); try { dataSource.setDriverClass("com.mysql.cj.jdbc.Driver"); } catch (PropertyVetoException e) { e.printStackTrace(); throw new RuntimeException(e); } dataSource.setJdbcUrl(url); dataSource.setUser(user); dataSource.setPassword(pwd); dataSource.setMinPoolSize(min_size); dataSource.setMaxPoolSize(max_size); dataSource.setCheckoutTimeout(time_out); dataSource.setMaxStatements(max_statement); boolean openAutoTestConn = Boolean.parseBoolean(config.getProperty("c3p0.open_auto_test_conn", "false")); if (openAutoTestConn) { // timeout, int test_conn_time = Integer.parseInt(config.getProperty("c3p0.idle_connection_test_period", "60")); dataSource.setTestConnectionOnCheckin(true); dataSource.setTestConnectionOnCheckout(false); dataSource.setIdleConnectionTestPeriod(test_conn_time); } } return dataSource; } /** * dao * * @return */ public static Connection popConnection() { // try { // System.out.println(" " + getDataSource().getMaxPoolSize()); // System.out.println(" " + getDataSource().getMinPoolSize()); // System.out.println(" " + getDataSource().getNumBusyConnections()); // System.out.println(" " + getDataSource().getNumIdleConnections()); // System.out.println(" " + getDataSource().getNumConnections()); // } catch (SQLException e1) { // e1.printStackTrace(); Connection conn = connections.get(); if (conn != null) { return conn; } try { return getDataSource().getConnection(); } catch (SQLException e) { e.printStackTrace(); throw new RuntimeException(e); } } /** * * * @throws SQLException SQL */ public static void beginTransaction() throws SQLException { Connection con = connections.get(); if (con != null) { throw new SQLException(""); } con = getDataSource().getConnection();// con con.setAutoCommit(false); connections.set(con); } /** * * * @throws SQLException SQL */ public static void commitTransaction() throws SQLException { Connection con = connections.get(); if (con == null) { throw new SQLException(""); } con.commit(); con.close(); con = null; connections.remove(); } /** * * * @throws SQLException SQL */ public static void rollbackTransaction() throws SQLException { Connection con = connections.get(); if (con == null) { throw new SQLException(""); } con.rollback(); con.close(); con = null; connections.remove(); } /** * Connection * * @param connection * @throws SQLException Sql */ public static void releaseConnection(Connection connection) throws SQLException { Connection con = connections.get(); if (connection != con) { if (connection != null && !connection.isClosed()) { connection.close(); } } } public Connection get() { if (debugConnection) { try { ServerConfig config = ServerConfig.getInstance(); String host = config.getProperty(MysqlConnection.rds_site, "127.0.0.1:3306"); String database = config.getProperty(MysqlConnection.rds_database, "appdb"); String url = String.format("jdbc:mysql://%s/%s?useSSL=false&autoReconnect=true&autoCommit=false&useUnicode=true&characterEncoding=utf8&serverTimezone=Asia/Shanghai", host, database); String user = config.getProperty(MysqlConnection.rds_username, "appdb_user"); String pwd = config.getProperty(MysqlConnection.rds_password, "appdb_password"); Class.forName("com.mysql.cj.jdbc.Driver"); if (host == null || user == null || pwd == null || database == null) { throw new RuntimeException("RDS"); } log.debug("create connection for mysql: " + host); return DriverManager.getConnection(url, user, pwd); } catch (ClassNotFoundException | SQLException e) { throw new RuntimeException(e); } } else { return this.connection; } } @Override public void close() { try { connection.close(); } catch (SQLException e) { e.printStackTrace(); } } public boolean isDebugConnection() { return debugConnection; } public void setDebugConnection(boolean debugConnection) { this.debugConnection = debugConnection; } }
package com.minegusta.mauswashere.listener; import com.google.common.base.Predicate; import com.google.common.collect.Collections2; import com.google.common.collect.Lists; import com.google.common.collect.Sets; import com.minegusta.mauswashere.RainBowStringMaker; import org.bukkit.*; import org.bukkit.block.Block; import org.bukkit.block.BlockFace; import org.bukkit.block.CreatureSpawner; import org.bukkit.enchantments.Enchantment; import org.bukkit.entity.Entity; import org.bukkit.entity.EntityType; import org.bukkit.entity.Player; import org.bukkit.entity.TNTPrimed; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.Listener; import org.bukkit.event.block.Action; import org.bukkit.event.block.BlockBreakEvent; import org.bukkit.event.block.BlockPlaceEvent; import org.bukkit.event.block.SignChangeEvent; import org.bukkit.event.entity.EntityDamageEvent; import org.bukkit.event.player.PlayerInteractEvent; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.meta.ItemMeta; import org.bukkit.util.Vector; import java.util.ArrayList; import java.util.Set; public class BlockListener implements Listener { @EventHandler public void onSignsCreateEvent(SignChangeEvent event) { String text1 = event.getLine(0); String text2 = event.getLine(1); String text3 = event.getLine(2); String text4 = event.getLine(3); if (event.getLine(0) != null) { event.setLine(0, ChatColor.translateAlternateColorCodes('&', text1)); if(text1.contains("&!")){ event.setLine(0, RainBowStringMaker.rainbowify(text1.replace("&!", ""))); } } if (event.getLine(1) != null) { event.setLine(1, ChatColor.translateAlternateColorCodes('&', text2)); if(text2.contains("&!")){ event.setLine(1, RainBowStringMaker.rainbowify(text2.replace("&!", ""))); } } if (event.getLine(2) != null) { event.setLine(2, ChatColor.translateAlternateColorCodes('&', text3)); if(text3.contains("&!")){ event.setLine(2, RainBowStringMaker.rainbowify(text3.replace("&!", ""))); } } if (event.getLine(3) != null) { event.setLine(3, ChatColor.translateAlternateColorCodes('&', text4)); if(text4.contains("&!")){ event.setLine(3, RainBowStringMaker.rainbowify(text4.replace("&!", ""))); } } if (text2 != null && (text2.equalsIgnoreCase("[command]") || text2.equalsIgnoreCase("[cmd]"))) { event.setLine(1, ChatColor.RED + "[Command]"); } if(text2 != null && text2.equalsIgnoreCase("[kit]")) { event.setLine(1, ChatColor.GREEN + "[Kit]"); } } @EventHandler(priority = EventPriority.MONITOR) public void onMineStuff(BlockBreakEvent e) { if (!(e.isCancelled()) && e.getPlayer().hasPermission("minegusta.donator")) { Material block = e.getBlock().getType(); if (block.equals(Material.MOB_SPAWNER)) { if (e.getPlayer().getItemInHand().containsEnchantment(Enchantment.LOOT_BONUS_BLOCKS)) { e.getPlayer().sendMessage(ChatColor.DARK_RED + "You cannot mine spawners with the fortune enchantment."); e.setCancelled(true); } else { CreatureSpawner spawner = (CreatureSpawner) e.getBlock().getState(); String mobType = "Pig"; EntityType entity = spawner.getSpawnedType(); switch (entity) { case PIG: mobType = ChatColor.LIGHT_PURPLE + "Pig"; break; case SKELETON: mobType = ChatColor.WHITE + "Skeleton"; break; case SPIDER: mobType = ChatColor.BLACK + "Spider"; break; case ZOMBIE: mobType = ChatColor.DARK_GREEN + "Zombie"; break; case CAVE_SPIDER: mobType = ChatColor.DARK_PURPLE + "Cave Spider"; break; case BLAZE: mobType = ChatColor.GOLD + "Blaze"; break; case SILVERFISH: mobType = ChatColor.GRAY + "SilverFish"; break; } ItemStack mobSpawner = new ItemStack(Material.MOB_SPAWNER, 1); ArrayList<String> spawnerType = Lists.newArrayList(); spawnerType.add(mobType + " Spawner"); ItemMeta meta = mobSpawner.getItemMeta(); meta.setLore(spawnerType); mobSpawner.setItemMeta(meta); e.getBlock().getWorld().dropItemNaturally(e.getBlock().getLocation(), mobSpawner); e.setExpToDrop(0); } } } } @EventHandler(priority = EventPriority.MONITOR) public void onBlockPlace(BlockPlaceEvent e) { Block block = e.getBlockPlaced(); ItemStack spawner = e.getItemInHand(); if (spawner.getType().equals(Material.MOB_SPAWNER) && !e.isCancelled()) { if (spawner.getItemMeta().hasLore()) { if (spawner.getItemMeta().getLore().toString().contains("Spawner")) { CreatureSpawner placedSpawner = (CreatureSpawner) block.getState(); if (spawner.getItemMeta().getLore().toString().contains("Pig")) { placedSpawner.setSpawnedType(EntityType.PIG); } else if (spawner.getItemMeta().getLore().toString().contains("Skeleton")) { placedSpawner.setSpawnedType(EntityType.SKELETON); } else if (spawner.getItemMeta().getLore().toString().contains("Spider")) { placedSpawner.setSpawnedType(EntityType.SPIDER); } else if (spawner.getItemMeta().getLore().toString().contains("Zombie")) { placedSpawner.setSpawnedType(EntityType.ZOMBIE); } else if (spawner.getItemMeta().getLore().toString().contains("Cave Spider")) { placedSpawner.setSpawnedType(EntityType.CAVE_SPIDER); } else if (spawner.getItemMeta().getLore().toString().contains("Blaze")) { placedSpawner.setSpawnedType(EntityType.BLAZE); } else if (spawner.getItemMeta().getLore().toString().contains("SilverFish")) { placedSpawner.setSpawnedType(EntityType.SILVERFISH); } placedSpawner.update(); } } } } //Cannons @EventHandler public void onCannonShoot(PlayerInteractEvent e) { Player player = e.getPlayer(); if ((e.getAction() == Action.RIGHT_CLICK_BLOCK) && (e.getClickedBlock().getType() == Material.STONE_BUTTON)) { Block l = e.getClickedBlock(); if ((l.getRelative(BlockFace.NORTH, 1).getType().equals(Material.IRON_BLOCK)) && (l.getRelative(BlockFace.NORTH, 2).getType().equals( Material.IRON_BLOCK)) && (l.getRelative(BlockFace.NORTH).getRelative(BlockFace.UP).getType().equals(Material.REDSTONE_TORCH_ON))) { Location barrel = e.getClickedBlock() .getRelative(BlockFace.NORTH, 2).getLocation(); player.getWorld().spigot().playEffect(barrel, Effect.CLOUD, 0, 0, 0.0F, 0.0F, 0.0F, 1.0F, 50, 2); player.playSound(player.getLocation(), Sound.EXPLODE, 0.5F, 2.0F); TNTPrimed tnt = (TNTPrimed) barrel.getWorld().spawn( barrel.add(0.0D, 0.7D, 0.0D), TNTPrimed.class); tnt.setVelocity(tnt.getLocation().getDirection().setY(0.4D) .setZ(-1).setX(0)); } if (l.getRelative(BlockFace.EAST, 1).getType().equals(Material.IRON_BLOCK) && !l.getRelative(BlockFace.EAST, 2).getType().equals( Material.IRON_BLOCK) && l.getRelative(BlockFace.EAST).getRelative(BlockFace.UP).getType() .equals(Material.REDSTONE_TORCH_ON)) { Location barrel = e.getClickedBlock() .getRelative(BlockFace.EAST, 2).getLocation(); player.getWorld() .spigot() .playEffect(barrel, Effect.CLOUD, 0, 0, 0.0F, 0.0F, 0.0F, 1.0F, 50, 2); player.playSound(player.getLocation(), Sound.EXPLODE, 0.5F, 2.0F); TNTPrimed tnt = barrel.getWorld().spawn(barrel.add(0.0D, 1.0D, 0.0D), TNTPrimed.class); tnt.setVelocity(tnt.getLocation().getDirection().setY(0.4D) .setX(1).setZ(0)); } if (l.getRelative(BlockFace.WEST, 1).getType().equals(Material.IRON_BLOCK)) { if (l.getRelative(BlockFace.WEST, 2).getType().equals( Material.IRON_BLOCK)) { if (l.getRelative(BlockFace.WEST).getRelative(BlockFace.UP).getType() .equals(Material.REDSTONE_TORCH_ON)) { Location barrel = e.getClickedBlock() .getRelative(BlockFace.WEST, 2).getLocation(); player.getWorld() .spigot() .playEffect(barrel, Effect.CLOUD, 0, 0, 0.0F, 0.0F, 0.0F, 1.0F, 50, 2); player.playSound(player.getLocation(), Sound.EXPLODE, 0.5F, 2.0F); TNTPrimed tnt = (TNTPrimed) barrel.getWorld().spawn(barrel.add(0.0D, 1.0D, 0.0D), TNTPrimed.class); tnt.setVelocity(tnt.getLocation().getDirection().setY(0.4D) .setX(-1).setZ(0)); } } } if (l.getRelative(BlockFace.SOUTH, 1).getType().equals(Material.IRON_BLOCK)) { if (l.getRelative(BlockFace.SOUTH, 2).getType().equals( Material.IRON_BLOCK)) { if (l.getRelative(BlockFace.SOUTH).getRelative(BlockFace.UP).getType() .equals(Material.REDSTONE_TORCH_ON)) { Location barrel = e.getClickedBlock() .getRelative(BlockFace.SOUTH, 2).getLocation(); player.getWorld() .spigot() .playEffect(barrel, Effect.CLOUD, 0, 0, 0.0F, 0.0F, 0.0F, 1.0F, 50, 2); player.playSound(player.getLocation(), Sound.EXPLODE, 0.5F, 2.0F); TNTPrimed tnt = (TNTPrimed) barrel.getWorld().spawn(barrel.add(0.0D, 1.0D, 0.0D), TNTPrimed.class); tnt.setVelocity(tnt.getLocation().getDirection().setY(0.4D) .setZ(1).setX(0)); } } } } } //Wool bounce. @EventHandler public void onWoolBounce(EntityDamageEvent e) { if (e.getCause().equals(EntityDamageEvent.DamageCause.FALL)) { if (e.getEntity().getType().equals(EntityType.PLAYER)) { Player player = (Player) e.getEntity(); if (player.getLocation().getBlock().getRelative(BlockFace.DOWN).getType().equals(Material.WOOL) && player.getLocation().getBlock() .getRelative(BlockFace.DOWN, 2).getType().equals(Material.WOOL) && !(player.isSneaking())) { e.setCancelled(true); player.getWorld().playSound(player.getLocation(), Sound.SLIME_WALK, 0.4F, 0.2F); Vector direction = player.getLocation().getDirection(); player.setVelocity(direction.setY(1).multiply(1.1)); } else if (player.getLocation().getBlock().getRelative(BlockFace.DOWN).getType().equals(Material.WOOL) && player.getLocation().getBlock() .getRelative(BlockFace.DOWN, 2).getType().equals(Material.WOOL) && player.isSneaking()) { e.setCancelled(true); } } } } //Jump pads public static Set<String> noFallDamage = Sets.newHashSet(); @EventHandler public void onPressurePress(PlayerInteractEvent e) { Player player = e.getPlayer(); if ((e.getAction() == Action.PHYSICAL) && (e.getClickedBlock().getType() == Material.STONE_PLATE)) { Block block = e.getClickedBlock().getRelative(BlockFace.DOWN); if (block.getType().equals(Material.LAPIS_BLOCK)) { player.getWorld().playSound(player.getLocation(), Sound.GHAST_FIREBALL, 1.0F, 1.0F); player.teleport(player.getLocation().add(0, 0.5, 0)); player.playEffect(player.getLocation(), Effect.SMOKE, 0); Vector v = player.getLocation().getDirection(); v.multiply(2.7); player.setVelocity(v); player.setVelocity(new Vector(player.getVelocity().getX(), 1.0D, player.getVelocity().getZ())); noFallDamage.add(player.getName()); } } } @EventHandler public void onLaunchLand(EntityDamageEvent e) { if (!e.getCause().equals(EntityDamageEvent.DamageCause.FALL) || !e.getEntity().getType().equals(EntityType.PLAYER)) return; String playerName = ((Player) e.getEntity()).getName(); if (!noFallDamage.contains(playerName)) return; e.setCancelled(true); noFallDamage.remove(playerName); } }
package edu.mit.streamjit.impl.distributed; import java.io.IOException; import java.util.HashMap; import java.util.Map; import com.google.common.collect.ImmutableMap; import edu.mit.streamjit.api.CompiledStream; import edu.mit.streamjit.api.Worker; import edu.mit.streamjit.impl.blob.Buffer; import edu.mit.streamjit.impl.blob.DrainData; import edu.mit.streamjit.impl.blob.Blob.Token; import edu.mit.streamjit.impl.common.Configuration; import edu.mit.streamjit.impl.distributed.common.CTRLRDrainElement; import edu.mit.streamjit.impl.distributed.common.Command; import edu.mit.streamjit.impl.distributed.common.ConfigurationString; import edu.mit.streamjit.impl.distributed.common.GlobalConstants; import edu.mit.streamjit.impl.distributed.common.BoundaryChannel.BoundaryInputChannel; import edu.mit.streamjit.impl.distributed.common.BoundaryChannel.BoundaryOutputChannel; import edu.mit.streamjit.impl.distributed.common.ConfigurationString.ConfigurationStringProcessor.ConfigType; import edu.mit.streamjit.impl.distributed.common.SNDrainElement.SNDrainProcessor; import edu.mit.streamjit.impl.distributed.common.TCPConnection.TCPConnectionInfo; import edu.mit.streamjit.impl.distributed.runtimer.Controller; import edu.mit.streamjit.impl.distributed.runtimer.CommunicationManager.StreamNodeAgent; public class StreamJitAppManager { private final Controller controller; private final StreamJitApp app; /** * A {@link BoundaryOutputChannel} for the head of the stream graph. If the * first {@link Worker} happened to fall outside the {@link Controller}, we * need to push the {@link CompiledStream}.offer() data to the first * {@link Worker} of the streamgraph. */ private BoundaryOutputChannel headChannel; /** * A {@link BoundaryInputChannel} for the tail of the whole stream graph. If * the sink {@link Worker} happened to fall outside the {@link Controller}, * we need to pull the sink's output in to the {@link Controller} in order * to make {@link CompiledStream} .pull() to work. */ private TailChannel tailChannel; private Thread headThread; private Thread tailThread; public StreamJitAppManager(Controller controller, StreamJitApp app) { this.controller = controller; this.app = app; controller.newApp(app); // TODO: Find a good calling place. } public void reconfigure() { Configuration.Builder builder = Configuration.builder(app .getDynamicConfiguration()); Map<Token, Map.Entry<Integer, Integer>> tokenMachineMap = new HashMap<>(); Map<Token, Integer> portIdMap = new HashMap<>(); Map<Token, TCPConnectionInfo> conInfoMap = controller.buildConInfoMap( app.partitionsMachineMap1, app.source1, app.sink1); builder.putExtraData(GlobalConstants.TOKEN_MACHINE_MAP, tokenMachineMap) .putExtraData(GlobalConstants.PORTID_MAP, portIdMap); builder.putExtraData(GlobalConstants.CONINFOMAP, conInfoMap); Configuration cfg = builder.build(); String jsonStirng = cfg.toJson(); ImmutableMap<Integer, DrainData> drainDataMap = app.getDrainData(); for (StreamNodeAgent node : controller.getStreamNodeMap().values()) { try { ConfigurationString json = new ConfigurationString(jsonStirng, ConfigType.DYNAMIC, drainDataMap.get(node.getNodeID())); node.writeObject(json); } catch (IOException e) { e.printStackTrace(); } } setupHeadTail1(conInfoMap, app.bufferMap, Token.createOverallInputToken(app.source1), Token.createOverallOutputToken(app.sink1)); start(); } /** * Setup the headchannel and tailchannel. * * @param cfg * @param bufferMap * @param headToken * @param tailToken */ private void setupHeadTail1(Map<Token, TCPConnectionInfo> conInfoMap, ImmutableMap<Token, Buffer> bufferMap, Token headToken, Token tailToken) { TCPConnectionInfo headconInfo = conInfoMap.get(headToken); assert headconInfo != null : "No head connection info exists in conInfoMap"; assert headconInfo.getSrcID() == controller.controllerNodeID : "Head channel should start from the controller."; if (!bufferMap.containsKey(headToken)) throw new IllegalArgumentException( "No head buffer in the passed bufferMap."); headChannel = new HeadChannel(bufferMap.get(headToken), controller.getConProvider(), headconInfo, "headChannel - " + headToken.toString(), 0); TCPConnectionInfo tailconInfo = conInfoMap.get(tailToken); assert tailconInfo != null : "No tail connection info exists in conInfoMap"; assert tailconInfo.getDstID() == controller.controllerNodeID : "Tail channel should ends at the controller."; if (!bufferMap.containsKey(tailToken)) throw new IllegalArgumentException( "No tail buffer in the passed bufferMap."); tailChannel = new TailChannel(bufferMap.get(tailToken), controller.getConProvider(), tailconInfo, "tailChannel - " + tailToken.toString(), 0, 10000); } /** * Start the execution of the StreamJit application. */ public void start() { if (headChannel != null) { headThread = new Thread(headChannel.getRunnable(), headChannel.name()); headThread.start(); } controller.sendToAll(Command.START); if (tailChannel != null) { tailChannel.reset(); tailThread = new Thread(tailChannel.getRunnable(), tailChannel.name()); tailThread.start(); } } public void drainingStarted(boolean isFinal) { if (headChannel != null) { headChannel.stop(isFinal); try { headThread.join(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } public void drain(Token blobID, boolean isFinal) { System.out.println("Drain requested to blob " + blobID); if (!app.blobtoMachineMap.containsKey(blobID)) throw new IllegalArgumentException(blobID + " not found in the blobtoMachineMap"); int machineID = app.blobtoMachineMap.get(blobID); StreamNodeAgent agent = controller.getStreamNodeMap().get(machineID); try { agent.writeObject(new CTRLRDrainElement.DoDrain(blobID, !isFinal)); } catch (IOException e) { e.printStackTrace(); } } public void drainingFinished(boolean isFinal) { System.out.println("App Manager : Draining Finished..."); tailChannel.reset(); if (tailChannel != null) { tailChannel.stop(); try { tailThread.join(); } catch (InterruptedException e) { e.printStackTrace(); } } if (isFinal) { controller.closeAll(); } } public void awaitForFixInput() throws InterruptedException { tailChannel.awaitForFixInput(); } // TODO: Temporary fix. Need to come up with a better solution to to set // DrainProcessor to StreamnodeAgent's messagevisitor. public void setDrainProcessor(SNDrainProcessor dp) { for (StreamNodeAgent agent : controller.getStreamNodeMap().values()) { agent.setDrainProcessor(dp); } } }
package cn.cerc.mis.core; import java.io.IOException; import java.lang.reflect.Method; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.google.gson.Gson; import cn.cerc.core.IHandle; import cn.cerc.db.core.IAppConfig; import cn.cerc.db.core.ServerConfig; import cn.cerc.mis.config.ApplicationProperties; import cn.cerc.mis.config.IAppStaticFile; import cn.cerc.mis.language.R; import cn.cerc.mis.other.BufferType; import cn.cerc.mis.other.MemoryBuffer; import cn.cerc.mis.page.JspPage; import cn.cerc.mis.page.RedirectPage; import lombok.extern.slf4j.Slf4j; @Slf4j public class StartForms implements Filter { @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { HttpServletRequest req = (HttpServletRequest) request; HttpServletResponse resp = (HttpServletResponse) response; String uri = req.getRequestURI(); int prefix = uri.indexOf("/", 2); if (prefix < 0) { IAppConfig conf = Application.getAppConfig(); resp.sendRedirect(String.format("%s", ApplicationProperties.App_Path, conf.getFormWelcome())); return; } IAppStaticFile staticFile = Application.getBean(IAppStaticFile.class, "appStaticFile", "appStaticFileDefault"); if (staticFile.isStaticFile(uri)) { // TODO jar if (uri.contains("imgZoom")) { chain.doFilter(req, resp); return; } /* * 1 getPathForms forms AppConfig * 2 3/ /131001/images/systeminstall-pc.png -> * /forms/images/systeminstall-pc.png */ log.debug("before {}", uri); IAppConfig conf = Application.getAppConfig(); String source = "/" + conf.getPathForms() + uri.substring(uri.indexOf("/", 2)); request.getServletContext().getRequestDispatcher(source).forward(request, response); log.debug("after {}", source); return; } log.info(uri); if (uri.contains("service/")) { chain.doFilter(req, resp); return; } if (uri.contains("task/")) { chain.doFilter(req, resp); return; } if (uri.contains("docs/")) { chain.doFilter(req, resp); return; } // 2Url String childCode = getRequestCode(req); if (childCode == null) { outputErrorPage(req, resp, new RuntimeException("" + req.getServletPath())); return; } String[] params = childCode.split("\\."); String formId = params[0]; String funcCode = params.length == 1 ? "execute" : params[1]; // TODO ??? req.setAttribute("logon", false); // TODO ??? IFormFilter formFilter = Application.getBean(IFormFilter.class, "AppFormFilter"); if (formFilter != null) { if (formFilter.doFilter(resp, formId, funcCode)) { return; } } try { IForm form = Application.getForm(req, resp, formId); if (form == null) { outputErrorPage(req, resp, new RuntimeException("error servlet:" + req.getServletPath())); return; } ClientDevice client = new ClientDevice(); client.setRequest(req); req.setAttribute("_showMenu_", !ClientDevice.APP_DEVICE_EE.equals(client.getDevice())); form.setClient(client); IHandle handle = Application.getHandle(); try { handle.setProperty(Application.sessionId, req.getSession().getId()); handle.setProperty(Application.deviceLanguage, client.getLanguage()); req.setAttribute("myappHandle", handle); form.setHandle(handle); log.debug(""); if (!form.logon()) { IAppLogin page = Application.getBean(IAppLogin.class, "appLogin", "appLoginManage", "appLoginDefault"); page.init(form); String cmd = page.checkToken(client.getToken()); if (cmd != null) { if (cmd.startsWith("redirect:")) { resp.sendRedirect(cmd.substring(9)); } else { String url = String.format("/WEB-INF/%s/%s", Application.getAppConfig().getPathForms(), cmd); request.getServletContext().getRequestDispatcher(url).forward(request, response); } } else { callForm(form, funcCode); } } else { callForm(form, funcCode); } } catch (Exception e) { outputErrorPage(req, resp, e); } finally { if (handle != null) { handle.close(); } } } catch (Exception e) { outputErrorPage(req, resp, e); } } private void outputErrorPage(HttpServletRequest request, HttpServletResponse response, Throwable e) throws ServletException, IOException { Throwable err = e.getCause(); if (err == null) { err = e; } IAppErrorPage errorPage = Application.getBean(IAppErrorPage.class, "appErrorPage", "appErrorPageDefault"); if (errorPage != null) { String result = errorPage.getErrorPage(request, response, err); if (result != null) { String url = String.format("/WEB-INF/%s/%s", Application.getAppConfig().getPathForms(), result); request.getServletContext().getRequestDispatcher(url).forward(request, response); } } else { log.warn("not define bean: errorPage"); log.error(err.getMessage()); err.printStackTrace(); } } protected IAppConfig createConfig() { return Application.getAppConfig(); } protected boolean checkEnableTime() { // Calendar cal = Calendar.getInstance(); // if (TDate.Today().compareTo(TDate.Today().monthEof()) == 0) { // if (cal.get(Calendar.HOUR_OF_DAY) >= 23) // throw new // RuntimeException("235"); // if (TDate.Today().compareTo(TDate.Today().monthBof()) == 0) // if (cal.get(Calendar.HOUR_OF_DAY) < 5) // throw new // RuntimeException("235"); return true; } protected boolean passDevice(IForm form) { // iPhone if (isExperienceAccount(form)) { return true; } String deviceId = form.getClient().getId(); // TODO String verifyCode = form.getRequest().getParameter("verifyCode"); log.debug(String.format(", deviceId=%s", deviceId)); String userId = (String) form.getHandle().getProperty(Application.userId); try (MemoryBuffer buff = new MemoryBuffer(BufferType.getSessionInfo, userId, deviceId)) { if (!buff.isNull()) { if (buff.getBoolean("VerifyMachine")) { log.debug(""); return true; } } boolean result = false; LocalService app = new LocalService(form.getHandle()); app.setService("SvrUserLogin.verifyMachine"); app.getDataIn().getHead().setField("deviceId", deviceId); if (verifyCode != null && !"".equals(verifyCode)) app.getDataIn().getHead().setField("verifyCode", verifyCode); if (app.exec()) { result = true; } else { int used = app.getDataOut().getHead().getInt("Used_"); if (used == 1) { result = true; } else { form.setParam("message", app.getMessage()); } } if (result) { buff.setField("VerifyMachine", true); } return result; } } protected void callForm(IForm form, String funcCode) throws ServletException, IOException { HttpServletResponse response = form.getResponse(); HttpServletRequest request = form.getRequest(); if ("excel".equals(funcCode)) { response.setContentType("application/vnd.ms-excel; charset=UTF-8"); response.addHeader("Content-Disposition", "attachment; filename=excel.csv"); } else { response.setContentType("text/html;charset=UTF-8"); } Object pageOutput = ""; String token = request.getParameter(RequestData.TOKEN); if (token == null || token.equals("")) { token = request.getSession().getId(); } Method method = null; long startTime = System.currentTimeMillis(); try { // FIXME: 2019/12/8 ??? CLIENTVER String CLIENTVER = request.getParameter("CLIENTVER"); if (CLIENTVER != null) { request.getSession().setAttribute("CLIENTVER", CLIENTVER); } if (!Application.getPassport(form.getHandle()).passForm(form)) { log.warn(String.format(" %s", request.getRequestURL())); throw new RuntimeException(R.asString(form.getHandle(), "")); } if (isExperienceAccount(form)) { try { if (form.getClient().isPhone()) { try { method = form.getClass().getMethod(funcCode + "_phone"); } catch (NoSuchMethodException e) { method = form.getClass().getMethod(funcCode); } } else { method = form.getClass().getMethod(funcCode); } pageOutput = method.invoke(form); } catch (PageException e) { form.setParam("message", e.getMessage()); pageOutput = e.getViewFile(); } } else { if (form.getHandle().getProperty(Application.userId) == null || form.passDevice() || passDevice(form)) { try { if (form.getClient().isPhone()) { try { method = form.getClass().getMethod(funcCode + "_phone"); } catch (NoSuchMethodException e) { method = form.getClass().getMethod(funcCode); } } else { method = form.getClass().getMethod(funcCode); } pageOutput = method.invoke(form); } catch (PageException e) { form.setParam("message", e.getMessage()); pageOutput = e.getViewFile(); } } else { log.debug(""); ServerConfig config = ServerConfig.getInstance(); String supCorpNo = config.getProperty("vine.mall.supCorpNo", ""); // APPiPhoneiPhone if (!"".equals(supCorpNo) && form.getClient().getDevice().equals(ClientDevice.APP_DEVICE_IPHONE)) { try { method = form.getClass().getMethod(funcCode + "_phone"); } catch (NoSuchMethodException e) { method = form.getClass().getMethod(funcCode); } form.getRequest().setAttribute("needVerify", "true"); pageOutput = method.invoke(form); } else { pageOutput = new RedirectPage(form, Application.getAppConfig().getFormVerifyDevice()); } } } if (pageOutput != null) { if (pageOutput instanceof IPage) { IPage output = (IPage) pageOutput; String cmd = output.execute(); if (cmd != null) { if (cmd.startsWith("redirect:")) { response.sendRedirect(cmd.substring(9)); } else { String url = String.format("/WEB-INF/%s/%s", Application.getAppConfig().getPathForms(), cmd); request.getServletContext().getRequestDispatcher(url).forward(request, response); } } } else { log.warn(String.format("%s pageOutput is not IPage: %s", funcCode, pageOutput)); JspPage output = new JspPage(form); output.setJspFile((String) pageOutput); output.execute(); } } } catch (Exception e) { outputErrorPage(request, response, e); } finally { if (method != null) { long timeout = 1000; Webpage webpage = method.getAnnotation(Webpage.class); if (webpage != null) { timeout = webpage.timeout(); } checkTimeout(form, funcCode, startTime, timeout); } } } protected void checkTimeout(IForm form, String funcCode, long startTime, long timeout) { long totalTime = System.currentTimeMillis() - startTime; if (totalTime > timeout) { String tmp[] = form.getClass().getName().split("\\."); String pageCode = tmp[tmp.length - 1] + "." + funcCode; String dataIn = new Gson().toJson(form.getRequest().getParameterMap()); if (dataIn.length() > 200) { dataIn = dataIn.substring(0, 200); } log.warn("pageCode: {}, tickCount: {}, dataIn: {}", pageCode, totalTime, dataIn); } } protected String getRequestCode(HttpServletRequest req) { String url = null; log.debug("servletPath {}", req.getServletPath()); String args[] = req.getServletPath().split("/"); if (args.length == 2 || args.length == 3) { if ("".equals(args[0]) && !"".equals(args[1])) { if (args.length == 3) { url = args[2]; } else { String token = (String) req.getAttribute(RequestData.TOKEN); IAppConfig conf = Application.getAppConfig(); if (token != null && !"".equals(token)) { url = conf.getFormDefault(); } else { url = conf.getFormWelcome(); } } } } return url; } protected boolean isExperienceAccount(IForm form) { return getIphoneAppstoreAccount().equals(form.getHandle().getUserCode()) || getBaseVerAccount().equals(form.getHandle().getUserCode()) || getLineWinderAccount().equals(form.getHandle().getUserCode()) || getTaiWanAccount().equals(form.getHandle().getUserCode()); } // iPhone protected String getIphoneAppstoreAccount() { return "15202406"; } protected String getBaseVerAccount() { return "16307405"; } // APPiPhone protected String getSimagoAccount() { return "47583201"; } // APPiPhone protected String getLineWinderAccount() { return "15531101"; } protected String getTaiWanAccount() { return "47598601"; } @Override public void init(FilterConfig filterConfig) throws ServletException { } @Override public void destroy() { } }
package org.teachingkidsprogramming.section03ifs; import org.teachingextensions.logo.Sound; import org.teachingextensions.logo.utils.EventUtils.MessageBox; public class HiLow { public static void main(String[] args) { // Choose a random number between 1 and 100 --#4.1 (fake!) & --#13 int answer = 11; for (int i = 1; i <= 8; i++) { int guess = MessageBox.askForNumericalInput("What is your guess?"); if (guess == answer) { Sound.playBeep(); MessageBox.showMessage("You Won!!!"); break; } else if (guess > answer) { MessageBox.showMessage("Too high"); } else { MessageBox.showMessage("Too low"); } if (i == 8) { MessageBox.showMessage("You lost"); } } } }
package edu.psu.compbio.seqcode.projects.naomi; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Set; import java.util.TreeMap; import org.apache.commons.math3.analysis.polynomials.PolynomialFunction; import org.apache.commons.math3.distribution.NormalDistribution; import pal.util.Comparator; import edu.psu.compbio.seqcode.deepseq.StrandedBaseCount; import edu.psu.compbio.seqcode.deepseq.experiments.ExperimentManager; import edu.psu.compbio.seqcode.deepseq.experiments.ExptConfig; import edu.psu.compbio.seqcode.deepseq.experiments.Sample; import edu.psu.compbio.seqcode.genome.Genome; import edu.psu.compbio.seqcode.genome.GenomeConfig; import edu.psu.compbio.seqcode.genome.location.Region; import edu.psu.compbio.seqcode.gse.gsebricks.verbs.location.ChromosomeGenerator; import edu.psu.compbio.seqcode.gse.tools.utils.Args; import edu.psu.compbio.seqcode.projects.seed.SEEDConfig; /** * DifferentialMSR: * * Methods refer to two papers * Probabilistic Multiscale Image Segmentation, Vincken et al. IEEE (1997) * * @author naomi yamada * **/ public class DifferentialMSR { protected GenomeConfig gconfig; protected ExptConfig econfig; protected SEEDConfig sconfig; protected int threePrimReadExt = 200; protected int binWidth = 1; protected Map<Region, HashMap<Integer,Set<Integer>>> segmentationTree = new HashMap<Region, HashMap<Integer, Set<Integer>>>(); public DifferentialMSR(GenomeConfig gcon, ExptConfig econ, SEEDConfig scon){ gconfig = gcon; econfig = econ; sconfig = scon; } public void buildMSR(){ /********************* * Gaussian scale space and window parameters */ // arbitrary number of scale int numScale= 20; double DELTA_TAU = 0.5*Math.log(2); double MINIMUM_VALUE = Math.pow(10, -100); //arbitrary minimum value; I cannot use Double.MIN_VALUE because it can become zero // I have to determine P_MIN value carefully because P_MIN will substantially affect Gaussian window size double P_MIN = Math.pow(10,-3); double K_MIN = 1/Math.sqrt(1-Math.exp(-2*DELTA_TAU)); double K_N = Math.ceil(K_MIN); /********************* * Linkage parameters */ double WEIGHT_I = 1.00; double WEIGHT_G = 0.0000001; double WEIGHT_M = 1000; /********************* * Matrices parameters */ double sigma[] = new double[numScale]; double radius[] = new double[numScale]; for (int i = 0; i<numScale;i++){ sigma[i] = 1; radius[i] = 1; } ExperimentManager manager = new ExperimentManager(econfig); Genome genome = gconfig.getGenome(); //test to print whole chromosomes System.out.println(genome.getChromList()); //fix here to get parameters only if they are specified binWidth = sconfig.getBinWidth(); threePrimReadExt = sconfig.getTag3PrimeExtension(); //test to print binWidth and threePrimReadExt System.out.println("binWidth is: "+binWidth); System.out.println("threePrimReadExt is: "+threePrimReadExt); Iterator<Region> chroms = new ChromosomeGenerator<Genome>().execute(genome); //iterating each chromosome (each chromosome is a region). while (chroms.hasNext()) { Region currChrom = chroms.next(); int currchromSize = currChrom.getWidth(); int currchromBinSize = (int) Math.ceil(currchromSize/binWidth); //primitive matrix to store signal and the subsequent convolved signals //its index correspond to the coordinates float[][] GaussianBlur = new float[currchromBinSize][2]; for (int i = 0;i<currchromBinSize;i++){ for (int j = 0; j<2;j++) GaussianBlur[i][j] = 0; } //get StrandedBaseCount list for each chromosome Map<Sample, List<StrandedBaseCount>> sampleCountsMap = new HashMap<Sample, List<StrandedBaseCount>>(); for (Sample sample : manager.getSamples()) sampleCountsMap.put(sample,sample.getBases(currChrom)); //StrandedBasedCount object contains positive and negative strand separately //store all base counts indexed by positions at column[1] //extend reads to 3' end and bin according to bin size for (Sample sample : manager.getSamples()){ List<StrandedBaseCount> currentCounts = sampleCountsMap.get(sample); for (StrandedBaseCount hits: currentCounts){ for (int i = 0; i<threePrimReadExt+1; i++){ if (hits.getStrand()=='+' && hits.getCoordinate()+i<currchromSize){ GaussianBlur[(int) Math.ceil((hits.getCoordinate()+i)/binWidth)][1]+=hits.getCount(); }else if (hits.getStrand()=='+' && hits.getCoordinate()-i >=0){ GaussianBlur[(int) Math.ceil((hits.getCoordinate()-i)/binWidth)][1]+=hits.getCount(); } } } currentCounts = null; } //testing // if (currchromSize > 200000000){ // System.out.println("current Chrom is: "+currChrom.getChrom()); // for (int i = 0; i< 100;i++) // System.out.println(GaussianBlur[(int) Math.ceil((92943501)/binWidth)+i][1]); /********************* * Starting nodes */ //linkageMap contains index of kids and parents HashMap <Integer, Integer> linkageMap = new HashMap<Integer, Integer>(); //adding starting nodes; to qualify for the starting nodes the signal intensity needs to be different from the subsequent signal intensity //adding the starting and end positions in the kids at start and end positions //setting max & min signal intensity float DImax = 0; float DImin = (float) Integer.MAX_VALUE; List <Integer> nonzeroList = new ArrayList<Integer>(); linkageMap.put(0,0); for (int i = 0 ; i< GaussianBlur.length-1; i++){ //should I start if (GaussianBlur[i][1] != GaussianBlur[i+1][1]) linkageMap.put(i,0); if (GaussianBlur[i][1] > DImax) DImax = GaussianBlur[i][1]; if (GaussianBlur[i][1] < DImin) DImin = GaussianBlur[i][1]; if (GaussianBlur[i][1]!=0) nonzeroList.add(i); } linkageMap.put(GaussianBlur.length-1,0); //copy to segmentation tree Map<Integer,Set<Integer>> currScale =new HashMap<Integer,Set<Integer>>(); currScale.put(0, linkageMap.keySet()); System.out.println("curr Scale 0 size: "+linkageMap.keySet().size()); //determine the first nonzero and last nonzero from signal int trailingZero = 0; int zeroEnd = 0; if (!nonzeroList.isEmpty()){ trailingZero = Collections.min(nonzeroList)-1; zeroEnd = Collections.max(nonzeroList)+1; } if (trailingZero == -1) trailingZero = 0; System.out.println("DImax is: "+DImax+"\t"+"DImin is: "+DImin+ "\t"+"trailingZero: "+trailingZero+"\t"+"zeroEnd"+"\t"+zeroEnd); for (int n = 1;n < numScale; n++){ /********************* * Gaussian scale space */ double polyCoeffi[] = new double [currchromBinSize]; //first copy from column[1] to column[0];this procedure need to be repeated for each iteration of scale //also copy from column[1] to array to store polynomial coefficient for (int i = 0 ; i<currchromBinSize; i++){ GaussianBlur[i][0]=GaussianBlur[i][1]; if (GaussianBlur[i][1] != 0){ polyCoeffi[i]=GaussianBlur[i][1]; }else{ polyCoeffi[i]=MINIMUM_VALUE; } } //sigma calculation sigma[n] = Math.exp(n*DELTA_TAU); // create normal distribution with mean zero and sigma[n] NormalDistribution normDistribution = new NormalDistribution(0.00,sigma[n]); //take inverse CDF based on the normal distribution using probability double inverseCDF = normDistribution.inverseCumulativeProbability(P_MIN); int windowSize = (int) (-Math.round(inverseCDF)*2+1); //window calculation based on Gaussian(normal) distribution with sigma, mean=zero,x=X[i] double window[] = new double[windowSize]; double windowSum = 0; for (int i = 0;i<windowSize;i++){ window[i] = normDistribution.density(Math.round(inverseCDF)+i); windowSum = windowSum+window[i]; } double normalizedWindow[]=new double[windowSize]; for (int i = 0;i<windowSize;i++) normalizedWindow[i] = window[i]/windowSum; PolynomialFunction poly1 = new PolynomialFunction(polyCoeffi); PolynomialFunction poly2 = new PolynomialFunction(normalizedWindow); PolynomialFunction polyMultiplication=poly1.multiply(poly2); double coefficients[]= polyMultiplication.getCoefficients(); //taking mid point of polynomial coefficients int polyMid = (int) Math.floor(coefficients.length/2); System.out.println("currchromBin Size is : "+currchromBinSize+"\t"+ "windowSize is: "+windowSize+"\t"+"coefficients length is: "+coefficients.length); //copy Gaussian blur results to the column[1] // I should check to make sure that it's not off by 1 for (int i = 0; i<currchromBinSize;i++){ if (currchromBinSize % 2 ==0 && coefficients.length/2 == 1) GaussianBlur[i][1]=(float) coefficients[polyMid-currchromBinSize/2+i+1]; else GaussianBlur[i][1]=(float) coefficients[polyMid-currchromBinSize/2+i]; } //testing; I can identify the region that I want to print using peak calling // if (currchromSize > 200000000){ // System.out.println("current Chrom is: "+currChrom.getChrom()); // for (int i = 0; i< 100;i++) // System.out.println(GaussianBlur[(int) Math.ceil((92943501)/binWidth)+i][0]+" : "+GaussianBlur[(int) Math.ceil((92943501)/binWidth)+i][1]); /*************** * Search Volume */ double tempRadius; if (n==1){ tempRadius = sigma[n]; }else{ tempRadius = Math.sqrt(Math.pow(sigma[n],2)-Math.pow(sigma[n-1], 2)); } radius[n] = Math.ceil(K_MIN*tempRadius); int DCPsize = (int) (Math.round(radius[n])*2+1); int dcp[] = new int[DCPsize]; double distanceFactor[] = new double[DCPsize]; double affectionDistance; double denom = -2*(Math.pow(sigma[n], 2)-Math.pow(sigma[n-1],2)); for (int i = 0; i<DCPsize;i++){ dcp[i] = (int) -Math.round(radius[n])+i; // applying equation 7 in Vincken(1997) affectionDistance=Math.exp(Math.pow(dcp[i], 2)/denom)/Math.exp(Math.pow(0.5*sigma[n],2)/denom); //applying equation 8 in Vincken (1997) if (Math.abs(dcp[i]) > 0.5*sigma[n]){distanceFactor[i]= affectionDistance;} else{distanceFactor[i] = 1.0000;} } /*************** * Linkage Loop */ TreeMap<Integer, Integer> GvParents = new TreeMap<Integer,Integer>(); /*********** * Over window */ //build segmentTree //First iteration only consider intensity differences between parent and kid and connect to the ones with the least difference. //From the second iteration, we consider ground volume = number of nodes that parents are linked to the kids //From third iteration, we increase the weight of the ground volume by 1e-7. //Vincken paper said after 3-4 iteration, there would be no significant difference. double groundVC = 0; double groundVPmax = 0; double tempScore = 0; //updating ground volume and iterating to encourage convergence for (int counter = 0; counter<5; counter++){ if (counter != 0){ for (Integer parent : GvParents.keySet()){ if ( GvParents.get(parent) > groundVPmax) groundVPmax = GvParents.get(parent); } } for (Integer kid : linkageMap.keySet()){ double intensityDiffScore = 0; for (int i = 0; i<DCPsize; i++){ if ((kid + dcp[i]) >=0 && (kid + dcp[i]) <currchromBinSize){ if (counter ==0 || groundVPmax == 0){groundVC = 0.00;} else{ groundVC = (WEIGHT_I+WEIGHT_G*counter)*GvParents.get(linkageMap.get(kid))/groundVPmax;} tempScore = distanceFactor[i]*((1- Math.abs(GaussianBlur[kid][0] - GaussianBlur[kid+dcp[i]][1])/DImax)+groundVC); if (tempScore > intensityDiffScore){ intensityDiffScore = tempScore; if (counter ==0){linkageMap.put(kid,(kid+dcp[i]));} else{ // if(GvParents.containsKey(kid+dcp[i])){linkageMap.put(kid,(kid+dcp[i]));} if(linkageMap.containsValue(kid+dcp[i])){linkageMap.put(kid,(kid+dcp[i]));} } } } } } //test // if (currchromSize > 200000000){ // System.out.println("current Chrom is: "+currChrom.getChrom()); // System.out.println("printing linkangeMap content"); // for (Map.Entry<Integer, Integer> entry : linkageMap.entrySet()){ // System.out.println("Key: "+entry.getKey()+" Value: "+entry.getValue()); GvParents.clear(); Integer lastParent = 0; Map<Integer, Integer> sortedLinkageMap = MapUtility.sortByValue(linkageMap); for (Integer parent : sortedLinkageMap.values()){ GvParents.put(parent, (parent-lastParent)); lastParent = parent; } GvParents.put(0, trailingZero); // I probably need to fix this later // GvParents.put(GvParents.firstKey(), trailingZero-GvParents.firstKey()); // GvParents.put(GaussianBlur.length,GaussianBlur.length-zeroEnd); //test if (currchromSize > 200000000){ System.out.println("current Chrom is: "+currChrom.getChrom()); System.out.println("printing GvParents content"); for (Map.Entry<Integer, Integer> entry : GvParents.entrySet()){ System.out.println("Key: "+entry.getKey()+" Value: "+entry.getValue()); } } } Map<Integer, Integer> sortedLinkageMap = MapUtility.sortByValue(linkageMap); linkageMap.clear(); for (Integer parent : sortedLinkageMap.values()){ linkageMap.put(parent, parent); } //for each scaleNum, add the parents to the segmentationTree currScale.put(n, GvParents.keySet()); }//end of scale space iteration for (Integer scale : currScale.keySet()){ System.out.println("current scale is: "+scale); Set<Integer> nodesSet = currScale.get(scale); System.out.println("current nodeset size is: "+nodesSet.size()); for (Integer node : nodesSet) System.out.println(node); } segmentationTree.put(currChrom, (HashMap<Integer, Set<Integer>>) currScale); }// end of chromosome iteration manager.close(); } public static void main(String[] args) { GenomeConfig gconf = new GenomeConfig(args); ExptConfig econf = new ExptConfig(gconf.getGenome(), args); SEEDConfig sconf = new SEEDConfig(gconf, args); DifferentialMSR profile = new DifferentialMSR (gconf, econf, sconf); profile.buildMSR(); } }
package com.oneliang.tools.builder.java.base; import java.util.List; import com.oneliang.tools.builder.base.Project; public class JavaProject extends Project { // use in building protected List<String> compileClasspathList = null; protected List<String> onlyCompileClasspathList = null; public JavaProject() { } public JavaProject(String workspace, String name) { super(workspace, name); } public JavaProject(String workspace, String name, String outputHome) { super(workspace, name, outputHome); } public void initialize() { super.initialize(); } /** * @return the compileClasspathList */ public List<String> getCompileClasspathList() { return compileClasspathList; } /** * @param compileClasspathList * the compileClasspathList to set */ public void setCompileClasspathList(List<String> compileClasspathList) { this.compileClasspathList = compileClasspathList; } /** * @return the onlyCompileClasspathList */ public List<String> getOnlyCompileClasspathList() { return onlyCompileClasspathList; } /** * @param onlyCompileClasspathList * the onlyCompileClasspathList to set */ public void setOnlyCompileClasspathList(List<String> onlyCompileClasspathList) { this.onlyCompileClasspathList = onlyCompileClasspathList; } }
package edu.stuy.commands.auton; import static edu.stuy.RobotMap.*; import edu.stuy.Robot; import edu.wpi.first.wpilibj.Timer; import edu.wpi.first.wpilibj.command.Command; import edu.wpi.first.wpilibj.smartdashboard.SmartDashboard; public class AutonDriveForwardInchesCommand extends Command { private double inches; private double startTime; private boolean usingCustomDistance; /** * If distance < 0, get it from SmartDashboard * @param dist */ public AutonDriveForwardInchesCommand(double dist) { // Use requires() here to declare subsystem dependencies // eg. requires(chassis); usingCustomDistance = dist < 0; inches = dist; requires(Robot.drivetrain); } // Called just before this Command runs the first time protected void initialize() { startTime = Timer.getFPGATimestamp(); Robot.drivetrain.resetEncoders(); } // Called repeatedly when this Command is scheduled to run protected void execute() { if (usingCustomDistance) { inches = SmartDashboard.getNumber(INCHES_LABEL); } double speed = getRampSpeed(); Robot.drivetrain.tankDrive(speed, speed); } /** * Ramping algorithm for linear acceleration and smooth velocity * Takes one second to ramp up to max speed * if t < 0.5, then speed = 2t^2; * if t < 1, then speed = -2t^2 + 4t - 1; * if t >= 1, then speed = 1; * @return the speed the robot should go at the current time */ private double getRampSpeed() { double t = Timer.getFPGATimestamp() - startTime; if (t < 0.5) { return 2 * t * t; } else if (t < 1) { return -2 * t * t + 4 * t - 1; } else { return 1; } } // Make this return true when this Command no longer needs to run execute() protected boolean isFinished() { return Robot.drivetrain.getDistance() >= inches || Timer.getFPGATimestamp() - startTime >= AUTON_DRIVETRAIN_TIMEOUT; } // Called once after isFinished returns true protected void end() { Robot.drivetrain.stop(); } // Called when another command which requires one or more of the same // subsystems is scheduled to run protected void interrupted() { } }
package edu.wpi.first.wpilibj.templates; import edu.wpi.first.wpilibj.DigitalInput; import edu.wpi.first.wpilibj.Encoder; import edu.wpi.first.wpilibj.IterativeRobot; import edu.wpi.first.wpilibj.Jaguar; import edu.wpi.first.wpilibj.Joystick; import edu.wpi.first.wpilibj.SpeedController; import edu.wpi.first.wpilibj.smartdashboard.SmartDashboard; /* * This program is used to test out the AS5145B encoder with the WPILIB Encoder class for incremental, quadrature input * * * wiring: * encoder to digital sidecar: * A and B pin on the encoder to SIG pins on the digital IO on the digital sidecar * both GND pins to two (or one if you want to solder them together) ground pins(-) on the digital IO on the digital sidecar * CSn pin to a ground pin (-) on the digital IO on the digital sidecar * 5V pin to a Power pin (PWR) on the digital IO on the digital sidecar * * optional wiring: * encoder to digital sidecar: * one wire to each the Mag DECn pin and the Mag INCn for testing to a signal pin(SIG) on the digital IO on the digital sidecar * see section 4.1 of the manual for pin descriptions */ public class IncrementalEncoderTest extends IterativeRobot { private final int CONTROLLER_PWM_OUT = 2; private final SpeedController speedController = new Jaguar(CONTROLLER_PWM_OUT); private final int A_QUADRATURE_INPUT = 5; private final int B_QUADRATURE_INPUT = 6; private final Encoder encoder = new Encoder(A_QUADRATURE_INPUT,B_QUADRATURE_INPUT); private final int JOYSTICK_DRIVER_STATION_POSITION = 1; private final int JOYSTICK_AXES = 2; // My joystick isn't typical, so I need to input the raw axis number Joystick joystick = new Joystick(JOYSTICK_DRIVER_STATION_POSITION); // these inputs are to test weather the magnetic encoder is in the correct field. // These don't need to be used. static final int MAGNETIC_FIELD_DECREASING_TEST = 4; static final int MAGNETIC_FIELD_INCREASING_TEST = 3; DigitalInput magdec = new DigitalInput(MAGNETIC_FIELD_DECREASING_TEST); DigitalInput maginc = new DigitalInput(MAGNETIC_FIELD_INCREASING_TEST); public void teleopInit() { //start recording changes in position encoder.start(); } public void teleopPeriodic() { // the encoder get function in normalized to 1024 ticks double rotations = ((double)encoder.get())/1024; System.out.println("rotation:" + rotations); SmartDashboard.putBoolean("direction", encoder.getDirection()); SmartDashboard.putBoolean("sStopped", encoder.getStopped()); SmartDashboard.putNumber("raw", encoder.getRaw()); SmartDashboard.putNumber("getcount", encoder.get()); SmartDashboard.putNumber("rotations", rotations); SmartDashboard.putBoolean("magdec", magdec.get()); SmartDashboard.putBoolean("maginc", maginc.get()); //control a motor with one of its axes, and make it go 10 times slower speedController.set(joystick.getRawAxis(JOYSTICK_AXES) * .1); } }
package org.spoofax.jsglr; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.io.Serializable; import aterm.ATerm; import aterm.ATermAppl; import aterm.ATermFactory; import aterm.ATermList; import aterm.AFun; public class ParseTable implements Serializable { static final long serialVersionUID = -3372429249660900093L; private State[] states; private int startState; private Label[] labels; private Priority[] priorities; private Associativity[] associativities; transient private ATermFactory factory; transient public AFun applAFun; transient public AFun ambAFun; private Label[] injections; public ParseTable(ATerm pt) throws InvalidParseTableException { parse(pt); initAFuns(pt.getFactory()); } public void initAFuns(ATermFactory factory) { this.factory = factory; applAFun = factory.makeAFun("appl", 2, false); ambAFun = factory.makeAFun("amb", 1, false); } public ATermFactory getFactory() { return factory; } private boolean parse(ATerm pt) throws InvalidParseTableException { int version = Term.intAt(pt, 0); startState = Term.intAt(pt, 1); ATermList labelsTerm = Term.listAt(pt, 2); ATermAppl statesTerm = Term.applAt(pt, 3); ATermAppl prioritiesTerm = Term.applAt(pt, 4); if (version != 4) { return false; } labels = parseLabels(labelsTerm); states = parseStates(statesTerm); priorities = parsePriorities(prioritiesTerm); associativities = parseAssociativities(prioritiesTerm); injections = new Label[labels.length]; for(int i=0;i<labels.length;i++) if(labels[i] != null && labels[i].isInjection()) injections[i] = labels[i]; return true; } private Priority[] parsePriorities(ATermAppl prioritiesTerm) throws InvalidParseTableException { ATermList prods = Term.listAt(prioritiesTerm, 0); List<Priority> ret = new ArrayList<Priority>(); for (int i = 0; i < prods.getChildCount(); i++) { ATermAppl a = Term.applAt(prods, i); int left = Term.intAt(a, 0); int right = Term.intAt(a, 1); if (a.getName().equals("left-prio")) { // handled by parseAssociativities } else if (a.getName().equals("right-prio")) { // handled by parseAssociativities } else if (a.getName().equals("non-assoc")) { // handled by parseAssociativities } else if (a.getName().equals("gtr-prio")) { if(left != right) ret.add(new Priority(Priority.GTR, left, right)); } else { throw new InvalidParseTableException("Unknown priority : " + a.getName()); } } return ret.toArray(new Priority[0]); } private Associativity[] parseAssociativities(ATermAppl prioritiesTerm) throws InvalidParseTableException { ATermList prods = Term.listAt(prioritiesTerm, 0); List<Associativity> ret = new ArrayList<Associativity>(); for (int i = 0; i < prods.getChildCount(); i++) { ATermAppl a = Term.applAt(prods, i); int left = Term.intAt(a, 0); int right = Term.intAt(a, 1); if (a.getName().equals("left-prio")) { if(left == right) ret.add(new Associativity(Priority.LEFT, left)); } else if (a.getName().equals("right-prio")) { if(left == right) ret.add(new Associativity(Priority.RIGHT, left)); } else if (a.getName().equals("non-assoc")) { if(left == right) ret.add(new Associativity(Priority.NONASSOC, left)); } else if (a.getName().equals("gtr-prio")) { // handled by parsePriorities } else { throw new InvalidParseTableException("Unknown priority : " + a.getName()); } } return ret.toArray(new Associativity[0]); } private Label[] parseLabels(ATermList labelsTerm) throws InvalidParseTableException { Label[] ret = new Label[labelsTerm.getChildCount() + 256 + 1]; for (int i = 0; i < labelsTerm.getChildCount(); i++) { ATermAppl a = Term.applAt(labelsTerm, i); ATermAppl prod = Term.applAt(a, 0); int labelNumber = Term.intAt(a, 1); boolean injection = isInjection(prod); ProductionAttributes pa = parseProductionAttributes(Term.applAt(prod, 2)); ret[labelNumber] = new Label(labelNumber, prod, pa, injection); } return ret; } private boolean isInjection(ATermAppl prod) { List r = prod.match("prod([<term>],cf(sort(<term>)),<term>)"); if (r != null && r.size() == 1) { ATerm x = (ATerm) r.get(0); return !(x.match("lit(<str>)") == null); } r = prod.match("prod([<term>],lex(sort(<str>)),<term>)"); if (r != null && r.size() == 1) { ATerm x = (ATerm) r.get(0); return !(x.match("lit(<str)") == null); } return false; } private ProductionAttributes parseProductionAttributes(ATermAppl attr) throws InvalidParseTableException { if (attr.getName().equals("attrs")) { ATermList ls = (ATermList) attr.getChildAt(0); int type = 0; ATerm term = null; for (int i = 0; i < ls.getChildCount(); i++) { ATermAppl t = (ATermAppl) ls.getChildAt(i); String ctor = t.getName(); if (ctor.equals("reject")) { type = ProductionAttributes.REJECT; } else if (ctor.equals("prefer")) { type = ProductionAttributes.PREFER; } else if (ctor.equals("avoid")) { type = ProductionAttributes.AVOID; } else if (ctor.equals("bracket")) { type = ProductionAttributes.BRACKET; } else if (ctor.equals("assoc")) { ATermAppl a = (ATermAppl) t.getChildAt(0); if (a.getName().equals("left")) { type = ProductionAttributes.LEFT_ASSOCIATIVE; } else if (a.getName().equals("right")) { type = ProductionAttributes.RIGHT_ASSOCIATIVE; } else { throw new InvalidParseTableException("Unknown assocativity: " + a.getName()); } } else if (ctor.equals("term")) { term = (ATerm) t.getChildAt(0).getChildAt(0); } else if (ctor.equals("id")) { // FIXME not certain about this term = (ATerm) t.getChildAt(0); } else { throw new InvalidParseTableException("Unknown attribute: " + t); } } return new ProductionAttributes(type, term); } else if (attr.getName().equals("no-attrs")) { return new ProductionAttributes(ProductionAttributes.NO_TYPE, null); } throw new InvalidParseTableException("Unknown attribute type: " + attr); } private State[] parseStates(ATermAppl statesTerm) throws InvalidParseTableException { ATermList states = Term.listAt(statesTerm, 0); State[] ret = new State[states.getLength()]; for (int i = 0; i < states.getLength(); i++) { ATermAppl stateRec = Term.applAt(states, i); int stateNumber = Term.intAt(stateRec, 0); Goto[] gotos = parseGotos(Term.listAt(stateRec, 1)); Action[] actions = parseActions(Term.listAt(stateRec, 2)); ret[i] = new State(stateNumber, gotos, actions); } return ret; } Map<Goto, Goto> gotoMap = new HashMap<Goto, Goto>(); private Goto makeGoto(int newStateNumber, Range[] ranges) { Goto g = new Goto(ranges, newStateNumber); if (gotoMap.containsKey(g)) { return gotoMap.get(g); } gotoMap.put(g, g); return g; } private Action[] parseActions(ATermList actionList) throws InvalidParseTableException { Action[] ret = new Action[actionList.getChildCount()]; for (int i = 0; i < actionList.getChildCount(); i++) { ATermAppl action = Term.applAt(actionList, i); Range[] ranges = parseRanges(Term.listAt(action, 0)); ActionItem[] items = parseActionItems(Term.listAt(action, 1)); ret[i] = new Action(ranges, items); } return ret; } private ActionItem[] parseActionItems(ATermList items) throws InvalidParseTableException { ActionItem[] ret = new ActionItem[items.getChildCount()]; for (int i = 0; i < items.getChildCount(); i++) { ActionItem item = null; ATermAppl a = Term.applAt(items, i); if (a.getName().equals("reduce") && a.getAFun().getArity() == 3) { int productionArity = Term.intAt(a, 0); int label = Term.intAt(a, 1); int status = Term.intAt(a, 2); item = makeReduce(productionArity, label, status); } else if(a.getName().equals("reduce") && a.getAFun().getArity() == 4) { int productionArity = Term.intAt(a, 0); int label = Term.intAt(a, 1); int status = Term.intAt(a, 2); Range[] charClasses = parseCharClasses(Term.listAt(a, 3)); item = makeReduceLookahead(productionArity, label, status, charClasses); } else if (a.getName().equals("accept")) { item = new Accept(); } else if (a.getName().equals("shift")) { int nextState = Term.intAt(a, 0); item = makeShift(nextState); } else { throw new InvalidParseTableException("Unknown action " + a.getName()); } ret[i] = item; } return ret; } private Range[] parseCharClasses(ATermList list) throws InvalidParseTableException { Range[] ret = new Range[list.getLength()]; for(int i=0;i<ret.length; i++) { ATerm t = list.getFirst(); list = list.getNext(); ATermList l = Term.listAt(Term.applAt(t, 0), 0); ATermList n = Term.listAt(t, 1); if(n.getLength() > 0) throw new InvalidParseTableException("Multiple lookahead not supported"); ret[i] = new Range(Term.intAt(l, 0), Term.intAt(l, 1)); } return ret; } private ActionItem makeReduceLookahead(int productionArity, int label, int status, Range[] charClasses) { return new ReduceLookahead(productionArity, label, status, charClasses); } Map<Reduce, Reduce> reduceMap = new HashMap<Reduce, Reduce>(); private Reduce makeReduce(int arity, int label, int status) { Reduce s = new Reduce(arity, label, status); if (reduceMap.containsKey(s)) { return reduceMap.get(s); } reduceMap.put(s, s); return s; } Map<Shift, Shift> shiftMap = new HashMap<Shift, Shift>(); private Shift makeShift(int nextState) { Shift s = new Shift(nextState); if (shiftMap.containsKey(s)) { return shiftMap.get(s); } shiftMap.put(s, s); return s; } private Goto[] parseGotos(ATermList gotos) throws InvalidParseTableException { Goto[] ret = new Goto[gotos.getChildCount()]; for (int i = 0; i < gotos.getChildCount(); i++) { ATermAppl go = Term.applAt(gotos, i); ATermList rangeList = Term.listAt(go, 0); int newStateNumber = Term.intAt(go, 1); Range[] ranges = parseRanges(rangeList); //int[] productionLabels = parseProductionLabels(rangeList); ret[i] = makeGoto(newStateNumber, ranges); } return ret; } // private int[] parseProductionLabels(ATermList ranges) throws InvalidParseTableException { // int[] ret = new int[ranges.getChildCount()]; // for (int i = 0; i < ranges.getChildCount(); i++) { // ATerm t = Term.termAt(ranges, i); // if (Term.isInt(t)) { // ret[i] = Term.toInt(t); // } else { //// else if(Term.isAppl(t) && ((ATermAppl)t).getName().equals("range")) { //// int s = Term.intAt(t, 0); //// int e = Term.intAt(t, 1); // Tools.debug(t); // throw new InvalidParseTableException(""); // return ret; private Range[] parseRanges(ATermList ranges) throws InvalidParseTableException { Range[] ret = new Range[ranges.getChildCount()]; for (int i = 0; i < ranges.getChildCount(); i++) { ATerm t = Term.termAt(ranges, i); if (Term.isInt(t)) { ret[i] = makeRange(Term.toInt(t)); } else { int low = Term.intAt(t, 0); int hi = Term.intAt(t, 1); ret[i] = makeRange(low, hi); } } return ret; } Map<Range, Range> rangeMap = new HashMap<Range, Range>(); private Range makeRange(int low, int hi) throws InvalidParseTableException { Range r = new Range(low, hi); if (rangeMap.containsKey(r)) { return rangeMap.get(r); } rangeMap.put(r, r); return r; } private Range makeRange(int n) throws InvalidParseTableException { return makeRange(n, n); } public State getInitialState() { return states[startState]; } public State go(State s, int label) { return states[s.go(label)]; } public Label getLabel(int label) { return labels[label]; } public State getState(int s) { return states[s]; } public int getStateCount() { return states.length; } public int getProductionCount() { return labels.length - 256; } public int getActionEntryCount() { int total = 0; for (State s : states) { total += s.getActionItemCount(); } return total; } public int getGotoCount() { int total = 0; for (State s : states) { total += s.getGotoCount(); } return total; } public int getActionCount() { int total = 0; for (State s : states) { total += s.getActionCount(); } return total; } public boolean hasRejects() { for (State s : states) { if (s.rejectable()) { return true; } } return false; } public boolean hasPriorities() { return priorities.length > 0 || associativities.length > 0; } public boolean hasPrefers() { for (State s : states) { if (s.hasPrefer()) { return true; } } return false; } public boolean hasAvoids() { for (State s : states) { if (s.hasAvoid()) { return true; } } return false; } public IParseNode lookupProduction(int currentToken) { return new ParseProductionNode(currentToken); } public ATerm getProduction(int prod) { if (prod < 256) { return factory.makeInt(prod); } return labels[prod].prod; } public List<Label> getPriorities(Label prodLabel) { List<Label> ret = new ArrayList<Label>(); for (Priority p : priorities) { if (p.left == prodLabel.labelNumber && p.type == Priority.GTR) { ret.add(labels[p.right]); } } return ret; } public Label lookupInjection(int prod) { return injections[prod]; } }
package com.shapesecurity.shift.parser; import com.google.common.collect.HashMultimap; import com.google.common.collect.Multimap; import com.google.common.collect.Multiset; import com.shapesecurity.functional.data.Monoid; import com.shapesecurity.shift.ast.*; import org.jetbrains.annotations.NotNull; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Member; import java.util.*; import java.util.function.Function; public class EarlyErrorContext { public static final Monoid<EarlyErrorContext> MONOID = new EarlyErrorContextMonoid(); @NotNull public final List<EarlyError> errors; // errors that are only errors in strict mode code @NotNull private final List<EarlyError> strictErrors; // Label values used in LabeledStatement nodes; cleared at function boundaries @NotNull private final Map<String, LabeledStatement> usedLabelNames; // BreakStatement nodes; cleared at iteration, switch, and function boundaries @NotNull private final List<BreakStatement> freeBreakStatements; // ContinueStatement nodes; cleared at iteration boundaries @NotNull private final List<ContinueStatement> freeContinueStatements; // labeled BreakStatement nodes; cleared at LabeledStatement with same Label and function boundaries @NotNull public final Map<String, BreakStatement> freeLabeledBreakStatements; // labeled ContinueStatement nodes; cleared at labeled iteration statement with same Label and function boundaries @NotNull public final Map<String, ContinueStatement> freeLabeledContinueStatements; // NewTargetExpression nodes; cleared at function (besides arrow expression) boundaries @NotNull public final List<NewTargetExpression> newTargetExpressions; // BindingIdentifier nodes; cleared at containing declaration node @NotNull public final Multimap<String, BindingIdentifier> boundNames; // BindingIdentifiers that were found to be in a lexical binding position @NotNull public final Multimap<String, BindingIdentifier> lexicallyDeclaredNames; // Previous BindingIdentifiers that were found to be in a lexical binding position @NotNull public Multimap<String, BindingIdentifier> previousLexicallyDeclaredNames; // BindingIdentifiers that were the name of a FunctionDeclaration @NotNull public final Multimap<String, BindingIdentifier> functionDeclarationNames; // BindingIdentifiers that were found to be in a variable binding position @NotNull public final Multimap<String, BindingIdentifier> varDeclaredNames; // BindingIdentifiers that were found to be in a variable binding position @NotNull public final List<BindingIdentifier> forOfVarDeclaredNames; // Names that this module exports @NotNull public final Multimap<String, BindingIdentifier> exportedNames; // Locally declared names that are referenced in export declarations @NotNull public final Multimap<String, BindingIdentifier> exportedBindings; // CallExpressions with Super callee @NotNull public final List<Super> superCallExpressions; // SuperCall expressions in the context of a Method named "constructor" @NotNull public final List<Super> superCallExpressionsInConstructorMethod; // MemberExpressions with Super object @NotNull public final List<MemberExpression> superPropertyExpressions; public EarlyErrorContext() { this( new ArrayList<>(), // errors new ArrayList<>(), // strictErrors new HashMap<>(), // usedLabelNames new ArrayList<>(), // freeBreakStatements new ArrayList<>(), // freeContinueStatements new HashMap<>(), // freeLabeledBreakStatements new HashMap<>(), // freeLabeledContinueStatements new ArrayList<>(), // newTargetExpressions HashMultimap.create(), // boundNames HashMultimap.create(), // lexicallyDeclaredNames HashMultimap.create(), // functionDeclarationNames HashMultimap.create(), // varDeclaredNames new ArrayList<>(), // forOfVarDeclaredNames HashMultimap.create(), // exportedNames HashMultimap.create(), // exportedBindings new ArrayList<>(), // superCallExpressions new ArrayList<>(), // superCallExpressionsInConstructorMethod new ArrayList<>() // superPropertyExpressions ); } public EarlyErrorContext( @NotNull List<EarlyError> errors, @NotNull List<EarlyError> strictErrors, @NotNull Map<String, LabeledStatement> usedLabelNames, @NotNull List<BreakStatement> freeBreakStatements, @NotNull List<ContinueStatement> freeContinueStatements, @NotNull Map<String, BreakStatement> freeLabeledBreakStatements, @NotNull Map<String, ContinueStatement> freeLabeledContinueStatements, @NotNull List<NewTargetExpression> newTargetExpressions, @NotNull Multimap<String, BindingIdentifier> boundNames, @NotNull Multimap<String, BindingIdentifier> lexicallyDeclaredNames, @NotNull Multimap<String, BindingIdentifier> functionDeclarationNames, @NotNull Multimap<String, BindingIdentifier> varDeclaredNames, @NotNull List<BindingIdentifier> forOfVarDeclaredNames, @NotNull Multimap<String, BindingIdentifier> exportedNames, @NotNull Multimap<String, BindingIdentifier> exportedBindings, @NotNull List<Super> superCallExpressions, @NotNull List<Super> superCallExpressionsInConstructorMethod, @NotNull List<MemberExpression> superPropertyExpressions ) { this.errors = errors; this.strictErrors = strictErrors; this.usedLabelNames = usedLabelNames; this.freeBreakStatements = freeBreakStatements; this.freeContinueStatements = freeContinueStatements; this.freeLabeledBreakStatements = freeLabeledBreakStatements; this.freeLabeledContinueStatements = freeLabeledContinueStatements; this.newTargetExpressions = newTargetExpressions; this.boundNames = boundNames; this.lexicallyDeclaredNames = lexicallyDeclaredNames; this.functionDeclarationNames = functionDeclarationNames; this.varDeclaredNames = varDeclaredNames; this.forOfVarDeclaredNames = forOfVarDeclaredNames; this.exportedNames = exportedNames; this.exportedBindings = exportedBindings; this.superCallExpressions = superCallExpressions; this.superCallExpressionsInConstructorMethod = superCallExpressionsInConstructorMethod; this.superPropertyExpressions = superPropertyExpressions; } @NotNull public EarlyErrorContext append(EarlyErrorContext other) { this.errors.addAll(other.errors); this.strictErrors.addAll(other.strictErrors); this.usedLabelNames.putAll(other.usedLabelNames); this.freeBreakStatements.addAll(other.freeBreakStatements); this.freeContinueStatements.addAll(other.freeContinueStatements); this.freeLabeledBreakStatements.putAll(other.freeLabeledBreakStatements); this.freeLabeledContinueStatements.putAll(other.freeLabeledContinueStatements); this.newTargetExpressions.addAll(other.newTargetExpressions); this.boundNames.putAll(other.boundNames); this.lexicallyDeclaredNames.putAll(other.lexicallyDeclaredNames); this.functionDeclarationNames.putAll(other.functionDeclarationNames); this.varDeclaredNames.putAll(other.varDeclaredNames); this.forOfVarDeclaredNames.addAll(other.forOfVarDeclaredNames); this.exportedNames.putAll(other.exportedNames); this.exportedBindings.putAll(other.exportedBindings); this.superCallExpressions.addAll(other.superCallExpressions); this.superCallExpressionsInConstructorMethod.addAll(other.superCallExpressionsInConstructorMethod); this.superPropertyExpressions.addAll(other.superPropertyExpressions); return this; } public EarlyErrorContext addFreeBreakStatement(BreakStatement s) { this.freeBreakStatements.add(s); return this; } public EarlyErrorContext addFreeLabeledBreakStatement(String string, BreakStatement s) { this.freeLabeledBreakStatements.put(string, s); return this; } public EarlyErrorContext clearFreeBreakStatements() { this.freeBreakStatements.clear(); return this; } public EarlyErrorContext addFreeContinueStatement(ContinueStatement s) { this.freeContinueStatements.add(s); return this; } public EarlyErrorContext addFreeLabeledContinueStatement(String string, ContinueStatement s) { this.freeLabeledContinueStatements.put(string, s); return this; } public EarlyErrorContext clearFreeContinueStatements() { this.freeContinueStatements.clear(); return this; } public EarlyErrorContext enforceFreeBreakStatementErrors(Function<BreakStatement, EarlyError> createError) { // [].push.apply(this.errors, this.freeBreakStatements.map(createError)); this.errors.addAll((Collection) this.freeBreakStatements.stream().map(createError::apply)); this.freeBreakStatements.clear(); return this; } public EarlyErrorContext enforceFreeLabeledBreakStatementErrors(Function<BreakStatement, EarlyError> createError) { // [].push.apply(this.errors, this.freeLabeledBreakStatements.map(createError)); this.errors.addAll((Collection) this.freeLabeledBreakStatements.values().stream().map(createError::apply)); this.freeLabeledBreakStatements.clear(); return this; } public EarlyErrorContext enforceFreeContinueStatementErrors(Function<ContinueStatement, EarlyError> createError) { // [].push.apply(this.errors, this.freeContinueStatements.map(createError)); this.errors.addAll((Collection) this.freeContinueStatements.stream().map(createError::apply)); this.freeContinueStatements.clear(); return this; } public EarlyErrorContext enforceFreeLabeledContinueStatementErrors(Function<ContinueStatement, EarlyError> createError) { // [].push.apply(this.errors, this.freeLabeledContinueStatements.map(createError)); this.errors.addAll((Collection) this.freeLabeledContinueStatements.values().stream().map(createError::apply)); this.freeLabeledContinueStatements.clear(); return this; } public EarlyErrorContext observeIterationLabel(String s, LabeledStatement label) { this.usedLabelNames.put(s, label); this.freeLabeledBreakStatements.remove(s); this.freeLabeledContinueStatements.remove(s); return this; } public EarlyErrorContext observeNonIterationLabel(String s, LabeledStatement label) { this.usedLabelNames.put(s, label); this.freeLabeledBreakStatements.remove(s); return this; } public EarlyErrorContext clearUsedLabelNames() { this.usedLabelNames.clear(); return this; } public EarlyErrorContext observeSuperCallExpression(Super node) { this.superCallExpressions.add(node); return this; } public EarlyErrorContext observeConstructorMethod() { this.superCallExpressionsInConstructorMethod.clear(); this.superCallExpressionsInConstructorMethod.addAll(this.superCallExpressions); this.superCallExpressions.clear(); return this; } public EarlyErrorContext clearSuperCallExpressionsInConstructorMethod() { this.superCallExpressionsInConstructorMethod.clear(); return this; } public EarlyErrorContext enforceSuperCallExpressions(Function<Super, EarlyError> createError) { // [].push.apply(this.errors, this.superCallExpressions.map(createError)); // [].push.apply(this.errors, this.superCallExpressionsInConstructorMethod.map(createError)); this.errors.addAll((Collection) this.superCallExpressions.stream().map(createError::apply)); this.errors.addAll((Collection) this.superCallExpressionsInConstructorMethod.stream().map(createError::apply)); this.superCallExpressions.clear(); this.superCallExpressionsInConstructorMethod.clear(); return this; } public EarlyErrorContext enforceSuperCallExpressionsInConstructorMethod(Function<Super, EarlyError> createError) { // [].push.apply(this.errors, this.superCallExpressionsInConstructorMethod.map(createError)); this.errors.addAll((Collection) this.superCallExpressionsInConstructorMethod.stream().map(createError::apply)); this.superCallExpressionsInConstructorMethod.clear(); return this; } public EarlyErrorContext observeSuperPropertyExpression(MemberExpression node) { this.superPropertyExpressions.add(node); return this; } public EarlyErrorContext clearSuperPropertyExpressions() { this.superPropertyExpressions.clear(); return this; } public EarlyErrorContext enforceSuperPropertyExpressions(Function<MemberExpression, EarlyError> createError) { // [].push.apply(this.errors, this.superPropertyExpressions.map(createError)); this.errors.addAll((Collection) this.superPropertyExpressions.stream().map(createError::apply)); this.superPropertyExpressions.clear(); return this; } public EarlyErrorContext observeNewTargetExpression(NewTargetExpression node) { this.newTargetExpressions.add(node); return this; } public EarlyErrorContext clearNewTargetExpressions() { this.newTargetExpressions.clear(); return this; } public EarlyErrorContext bindName(String name, BindingIdentifier node) { this.boundNames.put(name, node); return this; } public EarlyErrorContext clearBoundNames() { this.boundNames.clear(); return this; } public EarlyErrorContext observeLexicalDeclaration() { this.lexicallyDeclaredNames.putAll(this.boundNames); this.boundNames.clear(); return this; } public EarlyErrorContext observeLexicalBoundary() { this.previousLexicallyDeclaredNames = this.lexicallyDeclaredNames; this.lexicallyDeclaredNames.clear(); this.functionDeclarationNames.clear(); return this; } public EarlyErrorContext enforceDuplicateLexicallyDeclaredNames(Function<BindingIdentifier, EarlyError> createError) { // this.lexicallyDeclaredNames.forEachEntry((nodes/*, bindingName*/) => { // if (nodes.length > 1) { // nodes.slice(1).forEach(dupeNode => { // this.addError(createError(dupeNode)); for (String key: this.lexicallyDeclaredNames.keys()) { Collection<BindingIdentifier> nodes = this.lexicallyDeclaredNames.get(key); if (nodes.size() > 1) { for (BindingIdentifier node : nodes) { this.addError(createError.apply(node)); } } } return this; } public EarlyErrorContext enforceConflictingLexicallyDeclaredNames(ArrayList<String> otherNames, Function<BindingIdentifier, EarlyError> createError) { // this.lexicallyDeclaredNames.forEachEntry((nodes, bindingName) => { // if (otherNames.has(bindingName)) { // nodes.forEach(conflictingNode => { // this.addError(createError(conflictingNode)); for (Map.Entry<String, BindingIdentifier> entry : this.lexicallyDeclaredNames.entries()) { String bindingName = entry.getKey(); BindingIdentifier node = entry.getValue(); if (otherNames.contains(bindingName)) { this.addError(createError.apply(node)); } } return this; } public EarlyErrorContext observeFunctionDeclaration() { this.observeVarBoundary(); this.functionDeclarationNames.putAll(this.boundNames); this.boundNames.clear(); return this; } public EarlyErrorContext functionDeclarationNamesAreLexical() { this.lexicallyDeclaredNames.putAll(this.functionDeclarationNames); this.functionDeclarationNames.clear(); return this; } public EarlyErrorContext observeVarDeclaration() { this.varDeclaredNames.putAll(this.boundNames); this.boundNames.clear(); return this; } public EarlyErrorContext recordForOfVars() { // this.varDeclaredNames.forEach((bindingIdentifier) => { // this.forOfVarDeclaredNames.push(bindingIdentifier); this.forOfVarDeclaredNames.addAll(this.varDeclaredNames.values()); return this; } public EarlyErrorContext observeVarBoundary() { this.lexicallyDeclaredNames.clear(); this.functionDeclarationNames.clear(); this.varDeclaredNames.clear(); this.forOfVarDeclaredNames.clear(); return this; } public EarlyErrorContext exportName(String name, BindingIdentifier node) { this.exportedNames.put(name, node); return this; } public EarlyErrorContext exportDeclaredNames() { this.exportedNames.putAll(this.lexicallyDeclaredNames); this.exportedNames.putAll(this.varDeclaredNames); this.exportedBindings.putAll(this.lexicallyDeclaredNames); this.exportedBindings.putAll(this.varDeclaredNames); return this; } public EarlyErrorContext exportBinding(String name, BindingIdentifier node) { this.exportedBindings.put(name, node); return this; } public EarlyErrorContext clearExportedBindings() { this.exportedBindings.clear(); return this; } public EarlyErrorContext addError(EarlyError e) { this.errors.add(e); return this; } public EarlyErrorContext addStrictError(EarlyError e) { this.strictErrors.add(e); return this; } public EarlyErrorContext enforceStrictErrors() { // [].push.apply(this.errors, this.strictErrors); this.errors.addAll(this.strictErrors); this.strictErrors.clear(); return this; } private static final class EarlyErrorContextMonoid implements Monoid<EarlyErrorContext> { @NotNull @Override public EarlyErrorContext identity() { return new EarlyErrorContext(); } @NotNull @Override public EarlyErrorContext append(EarlyErrorContext a, EarlyErrorContext b) { return a.append(b); } } }
package emergencylanding.k.library.lwjgl.render; import java.awt.Color; import java.awt.Font; import java.awt.FontMetrics; import java.awt.Graphics2D; import java.awt.GraphicsEnvironment; import java.awt.RenderingHints; import java.awt.image.BufferedImage; import java.util.HashMap; import java.util.Map; import k.core.util.arrays.ResizableArray; import emergencylanding.k.library.lwjgl.Shapes; import emergencylanding.k.library.lwjgl.tex.BufferedTexture; import emergencylanding.k.library.lwjgl.tex.ELTexture; import emergencylanding.k.library.util.LUtils; public class StringRenderer { public final static int ALIGN_LEFT = 0, ALIGN_RIGHT = 1, ALIGN_CENTER = 2; /** Array that holds necessary information about the font characters */ private ELTexture[] charArray = new ELTexture[256]; /** Map of user defined font characters (Character <-> IntObject) */ private Map<Character, ELTexture> customChars = new HashMap<Character, ELTexture>(); /** Boolean flag on whether AntiAliasing is enabled or not */ private boolean antiAlias; /** Font's size */ private int fontSize = 0; /** Height */ private int fontHeight; /** A reference to Java's AWT Font that we create our font texture from */ private Font font; /** The font metrics for our Java AWT font */ private FontMetrics fontMetrics; private int correctL = 9, correctR = 8; public StringRenderer(Font font, boolean antiAlias, char[] additionalChars) { this.font = font; this.fontSize = font.getSize() + 3; this.antiAlias = antiAlias; createSet(additionalChars); } public StringRenderer(Font font, boolean antiAlias) { this(font, antiAlias, null); } public void setCorrection(boolean on) { if (on) { correctL = 2; correctR = 1; } else { correctL = 0; correctR = 0; } } private BufferedImage getFontImage(char ch) { // Create a temporary image to extract the character's size BufferedImage tempfontImage = new BufferedImage(1, 1, BufferedImage.TYPE_INT_ARGB); Graphics2D g = (Graphics2D) tempfontImage.getGraphics(); if (antiAlias == true) { g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); } g.setFont(font); fontMetrics = g.getFontMetrics(); int charwidth = fontMetrics.charWidth(ch) + 8; if (charwidth <= 0) { charwidth = 7; } int charheight = fontMetrics.getHeight() + 3; if (charheight <= 0) { charheight = fontSize; } // Create another image holding the character we are creating BufferedImage fontImage; fontImage = new BufferedImage(charwidth, charheight, BufferedImage.TYPE_INT_ARGB); Graphics2D gt = (Graphics2D) fontImage.getGraphics(); if (antiAlias == true) { gt.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); } gt.setFont(font); gt.setColor(Color.WHITE); int charx = 3; int chary = 1; gt.drawString(String.valueOf(ch), (charx), (chary) + fontMetrics.getAscent()); return fontImage; } private void createSet(char[] customCharsArray) { try { int customCharsLength = (customCharsArray != null) ? customCharsArray.length : 0; for (int i = 0; i < 256 + customCharsLength; i++) { // get 0-255 characters and then custom characters char ch = (i < 256) ? (char) i : customCharsArray[i - 256]; // create image BufferedImage fontImage = getFontImage(ch); // inc height if needed fontHeight = Math.max(fontHeight, fontImage.getHeight()); if (i < 256) { // standard characters charArray[i] = new BufferedTexture(fontImage); } else { // custom characters customChars.put(new Character(ch), new BufferedTexture( fontImage)); } } } catch (Exception e) { LUtils.print("Failed to create font."); e.printStackTrace(); } } private void drawQuad(float drawX, float drawY, float drawX2, float drawY2, ELTexture tex) { Shapes.getQuad(new VertexData().setXYZ(drawX2, drawY2, 0), new VertexData().setXYZ(drawX, drawY, 0), Shapes.XY) .setTexture(tex).draw().destroy(); } public int getWidth(String whatchars) { int totalwidth = 0; int currentChar = 0; for (int i = 0; i < whatchars.length(); i++) { currentChar = whatchars.charAt(i); ELTexture tex = (currentChar < 256) ? charArray[currentChar] : customChars.get(new Character((char) currentChar)); if (tex != null) totalwidth += tex.dim.width; } return totalwidth; } public int getHeight() { return fontHeight; } public int getHeight(String HeightString) { return fontHeight; } public int getLineHeight() { return fontHeight; } public void drawString(float x, float y, String whatchars, float scaleX, float scaleY) { drawString(x, y, whatchars, 0, whatchars.length() - 1, scaleX, scaleY, ALIGN_LEFT); } public void drawString(float x, float y, String whatchars, float scaleX, float scaleY, int format) { drawString(x, y, whatchars, 0, whatchars.length() - 1, scaleX, scaleY, format); } public void drawString(float x, float y, String whatchars, int startIndex, int endIndex, float scaleX, float scaleY, int format) { ELTexture tex = null; int charCurrent; int totalwidth = 0; int i = startIndex, d, c; float startY = 0; switch (format) { case ALIGN_RIGHT: { d = -1; c = correctR; while (i < endIndex) { if (whatchars.charAt(i) == '\n') startY -= fontHeight; i++; } break; } case ALIGN_CENTER: { for (int l = startIndex; l <= endIndex; l++) { charCurrent = whatchars.charAt(l); if (charCurrent == '\n') break; if (charCurrent < 256) { tex = charArray[charCurrent]; } else { tex = customChars.get(new Character((char) charCurrent)); } totalwidth += tex.dim.width - correctL; } totalwidth /= -2; } case ALIGN_LEFT: default: { d = 1; c = correctL; break; } } while (i >= startIndex && i <= endIndex) { charCurrent = whatchars.charAt(i); if (charCurrent < 256) { tex = charArray[charCurrent]; } else { tex = customChars.get(new Character((char) charCurrent)); } if (tex != null) { if (d < 0) totalwidth += (tex.dim.width - c) * d; if (charCurrent == '\n') { startY -= fontHeight * d; totalwidth = 0; if (format == ALIGN_CENTER) { for (int l = i + 1; l <= endIndex; l++) { charCurrent = whatchars.charAt(l); if (charCurrent == '\n') break; if (charCurrent < 256) { tex = charArray[charCurrent]; } else { tex = customChars.get(new Character( (char) charCurrent)); } totalwidth += tex.dim.width - correctL; } totalwidth /= -2; } // if center get next lines total width/2; } else { drawQuad((totalwidth + tex.dim.width) * scaleX + x, startY * scaleY + y, totalwidth * scaleX + x, (startY + tex.dim.height) * scaleY + y, tex); if (d > 0) totalwidth += (tex.dim.width - c) * d; } i += d; } } } public static boolean isSupported(String fontname) { Font font[] = getFonts(); for (int i = font.length - 1; i >= 0; i if (font[i].getName().equalsIgnoreCase(fontname)) return true; } return false; } public static Font[] getFonts() { return GraphicsEnvironment.getLocalGraphicsEnvironment().getAllFonts(); } public static byte[] intToByteArray(int value) { return new byte[] { (byte) (value >>> 24), (byte) (value >>> 16), (byte) (value >>> 8), (byte) value }; } public void destroy() { ELTexture[] all = new ELTexture[charArray.length + customChars.size()]; System.arraycopy(charArray, 0, all, 0, charArray.length); char[] c = new ResizableArray<char[]>(char[].class, customChars.values()).getArray(); System.arraycopy(c, 0, all, charArray.length, c.length); for (ELTexture t : all) { t.kill(); } } }
package com.sibilantsolutions.iptools.test; import java.io.IOException; import java.net.InetAddress; import java.net.ServerSocket; import java.net.Socket; import javax.net.ServerSocketFactory; import org.kohsuke.args4j.CmdLineException; import org.kohsuke.args4j.CmdLineParser; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.beust.jcommander.JCommander; import com.sibilantsolutions.iptools.cli.CommandAggregator; import com.sibilantsolutions.iptools.cli.CommandHttp; import com.sibilantsolutions.iptools.cli.CommandIrc; import com.sibilantsolutions.iptools.cli.CommandRedir; import com.sibilantsolutions.iptools.cli.CommandSocketTwoPane; import com.sibilantsolutions.iptools.event.ConnectEvent; import com.sibilantsolutions.iptools.event.ConnectionListenerI; import com.sibilantsolutions.iptools.gui.SocketTwoPane; import com.sibilantsolutions.iptools.redir.Redirector; public class IpToolsTester { final static private Logger log = LoggerFactory.getLogger( IpToolsTester.class ); static private String[] args; static public void main( String[] args ) { try { long startMs = System.currentTimeMillis(); log.info( "main() started." ); IpToolsTester.args = args; new SocketTwoPane().buildUi(); //new IpToolsTester().test(); // new IpToolsTester().ircTest(); // new IpToolsTester().jCommanderTest( args ); // new IpToolsTester().args4jTest( args ); long endMs = System.currentTimeMillis(); log.info( "main() finished; duration={} ms.", endMs - startMs ); } catch( Exception e ) { log.error( "Trouble:", new RuntimeException( e ) ); } } private void args4jTest( String[] args ) { CommandAggregator bean = new CommandAggregator(); CmdLineParser parser = new CmdLineParser( bean ); try { log.info( "Printing usage." ); parser.printUsage( System.out ); log.info( "Done printing usage." ); parser.parseArgument( args ); log.info( "Printing usage." ); parser.printSingleLineUsage( System.out ); log.info( "Done printing usage." ); log.info( "cmd={}", bean.cmd ); CommandIrc irc = (CommandIrc)bean.cmd; log.info( "file={}", irc.getFilename() ); } catch ( CmdLineException e ) { // TODO Auto-generated catch block throw new UnsupportedOperationException( "OGTE TODO!", e ); } } private void jCommanderTest( String[] args ) { JCommander jc = new JCommander(); jc.addCommand( CommandIrc.COMMAND_NAME, CommandIrc.INSTANCE, CommandIrc.ALIASES ); jc.addCommand( CommandRedir.COMMAND_NAME, CommandRedir.INSTANCE, CommandRedir.ALIASES ); jc.addCommand( CommandSocketTwoPane.COMMAND_NAME, CommandSocketTwoPane.INSTANCE, CommandSocketTwoPane.ALIASES ); jc.addCommand( CommandHttp.COMMAND_NAME, CommandHttp.INSTANCE, CommandHttp.ALIASES ); jc.usage(); jc.parse( args ); String parsedCommand = jc.getParsedCommand(); switch ( parsedCommand ) { case CommandIrc.COMMAND_NAME: String filename = CommandIrc.INSTANCE.getFilename(); log.info( "IRC filename={}.", filename ); break; case CommandRedir.COMMAND_NAME: log.info( "Redir." ); break; default: throw new RuntimeException( "OGTE TODO" ); } } private void test() { ServerSocketFactory ssf = ServerSocketFactory.getDefault(); try { InetAddress loopback = InetAddress.getByName( null ); final ServerSocket serverSocket = ssf.createServerSocket( 8888, 50, loopback ); log.info( "Created server socket={}.", serverSocket ); boolean isRunning = true; while ( isRunning ) { log.info( "Waiting to accept connection={}.", serverSocket ); final Socket socket = serverSocket.accept(); log.info( "Accepted connection={} from server={}.", socket, serverSocket ); Runnable r = new Runnable() { @Override public void run() { log.info( "Started onConnect thread={} for socket={}.", Thread.currentThread(), socket ); //ConnectionListenerI connListener = httpConnectionListener(); ConnectionListenerI connListener = redirConnectionListener(); connListener.onConnect( new ConnectEvent( socket, serverSocket ) ); log.info( "Finished onConnect thread={} for socket={}.", Thread.currentThread(), socket ); } }; //Start the onConnect thread immediately after accept, so that the server //can accept another connection right away. new Thread( r ).start(); } } catch ( IOException e ) { throw new RuntimeException( "Trouble with socketry:", e ); } } private ConnectionListenerI redirConnectionListener() { Redirector redirector = new Redirector(); redirector.setTargetHost( args[0] ); redirector.setTargetPort( Integer.parseInt( args[1] ) ); redirector.setTargetSsl( Boolean.parseBoolean( args[2] ) ); return redirector; } }
package net.somethingdreadful.MAL; import android.annotation.TargetApi; import android.content.Context; import android.content.Intent; import android.content.res.Configuration; import android.content.res.Resources; import android.net.Uri; import android.nfc.NdefMessage; import android.nfc.NdefRecord; import android.nfc.NfcAdapter; import android.os.Build; import android.os.Bundle; import android.os.Parcelable; import android.support.v4.app.FragmentManager; import android.support.v4.widget.SwipeRefreshLayout; import android.text.Html; import android.text.method.LinkMovementMethod; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.RatingBar; import android.widget.RatingBar.OnRatingBarChangeListener; import android.widget.RelativeLayout; import com.squareup.picasso.Callback; import com.squareup.picasso.Picasso; import net.somethingdreadful.MAL.api.MALApi; import net.somethingdreadful.MAL.api.MALApi.ListType; import net.somethingdreadful.MAL.api.response.Anime; import net.somethingdreadful.MAL.api.response.GenericRecord; import net.somethingdreadful.MAL.api.response.Manga; import net.somethingdreadful.MAL.dialog.EpisodesPickerDialogFragment; import net.somethingdreadful.MAL.dialog.MangaPickerDialogFragment; import net.somethingdreadful.MAL.dialog.RemoveConfirmationDialogFragment; import net.somethingdreadful.MAL.dialog.StatusPickerDialogFragment; import net.somethingdreadful.MAL.dialog.UpdatePasswordDialogFragment; import net.somethingdreadful.MAL.tasks.APIAuthenticationErrorListener; import net.somethingdreadful.MAL.tasks.NetworkTask; import net.somethingdreadful.MAL.tasks.NetworkTaskCallbackListener; import net.somethingdreadful.MAL.tasks.TaskJob; import net.somethingdreadful.MAL.tasks.WriteDetailTask; import org.apache.commons.lang3.text.WordUtils; import org.holoeverywhere.app.Activity; import org.holoeverywhere.widget.TextView; import java.io.Serializable; import java.nio.charset.Charset; import java.util.Locale; import de.keyboardsurfer.android.widget.crouton.Crouton; import de.keyboardsurfer.android.widget.crouton.Style; public class DetailView extends Activity implements Serializable, OnRatingBarChangeListener, NetworkTaskCallbackListener, Card.onCardClickListener, APIAuthenticationErrorListener, SwipeRefreshLayout.OnRefreshListener { public ListType type; public Anime animeRecord; public Manga mangaRecord; SwipeRefreshLayout swipeRefresh; int recordID; Context context; PrefManager pref; Menu menu; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_detailview); getSupportActionBar().setDisplayHomeAsUpEnabled(true); ((Card) findViewById(R.id.detailCoverImage)).setContent(R.layout.card_detailview_image); ((Card) findViewById(R.id.synopsis)).setContent(R.layout.card_detailview_synopsis); ((Card) findViewById(R.id.mediainfo)).setContent(R.layout.card_detailview_mediainfo); ((Card) findViewById(R.id.status)).setContent(R.layout.card_detailview_status); ((Card) findViewById(R.id.progress)).setContent(R.layout.card_detailview_progress); ((Card) findViewById(R.id.rating)).setContent(R.layout.card_detailview_rating); type = (ListType) getIntent().getSerializableExtra("recordType"); if (type.equals(ListType.ANIME)) animeRecord = (Anime) getIntent().getSerializableExtra("record"); else mangaRecord = (Manga) getIntent().getSerializableExtra("record"); recordID = (type.equals(ListType.ANIME) ? animeRecord.getId() : mangaRecord.getId()); context = getApplicationContext(); pref = new PrefManager(context); setCard(); setListener(); if (savedInstanceState == null) { setText(); } else { animeRecord = (Anime) savedInstanceState.getSerializable("anime"); mangaRecord = (Manga) savedInstanceState.getSerializable("manga"); setText(); } } @Override public void onRefresh() { getRecord(); } @Override protected void onSaveInstanceState(Bundle State) { super.onSaveInstanceState(State); State.putSerializable("anime", animeRecord); State.putSerializable("manga", mangaRecord); } @Override public void onConfigurationChanged(Configuration newConfig) { super.onConfigurationChanged(newConfig); setContentView(R.layout.activity_detailview); ((Card) findViewById(R.id.detailCoverImage)).setContent(R.layout.card_detailview_image); ((Card) findViewById(R.id.synopsis)).setContent(R.layout.card_detailview_synopsis); ((Card) findViewById(R.id.mediainfo)).setContent(R.layout.card_detailview_mediainfo); ((Card) findViewById(R.id.status)).setContent(R.layout.card_detailview_status); ((Card) findViewById(R.id.progress)).setContent(R.layout.card_detailview_progress); ((Card) findViewById(R.id.rating)).setContent(R.layout.card_detailview_rating); setCard(); setText(); setListener(); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.activity_detail_view, menu); return true; } @Override public boolean onPrepareOptionsMenu(Menu menu) { this.menu = menu; if (animeRecord != null || mangaRecord != null) setMenu(); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case android.R.id.home: finish(); break; case R.id.action_Share: Share(); break; case R.id.action_Remove: showRemoveDialog(); break; case R.id.action_addToList: addToList(); break; case R.id.action_ViewMALPage: Uri malurl = Uri.parse("http://myanimelist.net/" + type.toString().toLowerCase(Locale.US) + "/" + recordID + "/"); startActivity(new Intent(Intent.ACTION_VIEW, malurl)); break; } return true; } /* * set all the ClickListeners */ public void setListener() { ((RatingBar) findViewById(R.id.MyScoreBar)).setOnRatingBarChangeListener(this); ((Card) findViewById(R.id.status)).setCardClickListener(this); ((Card) findViewById(R.id.progress)).setCardClickListener(this); swipeRefresh = (SwipeRefreshLayout) findViewById(R.id.swiperefresh); swipeRefresh.setOnRefreshListener(this); swipeRefresh.setColorScheme(R.color.holo_blue_bright, R.color.holo_green_light, R.color.holo_orange_light, R.color.holo_red_light); swipeRefresh.setEnabled(true); } /* * Manage the progress card */ public void setCard() { if (type != null && type.equals(ListType.ANIME)) { TextView progresslabel1 = (TextView) findViewById(R.id.progresslabel1); progresslabel1.setText(getString(R.string.card_content_episodes)); TextView progresslabel2 = (TextView) findViewById(R.id.progresslabel2); progresslabel2.setVisibility(View.GONE); TextView progresslabel2Current = (TextView) findViewById(R.id.progresslabel2Current); progresslabel2Current.setVisibility(View.GONE); TextView progresslabel2Total = (TextView) findViewById(R.id.progresslabel2Total); progresslabel2Total.setVisibility(View.GONE); } } /* * set the right menu items. */ public void setMenu() { if (menu != null) { if (isAdded()) { menu.findItem(R.id.action_Remove).setVisible(true); menu.findItem(R.id.action_addToList).setVisible(false); } else { menu.findItem(R.id.action_Remove).setVisible(false); menu.findItem(R.id.action_addToList).setVisible(true); } if (MALApi.isNetworkAvailable(context) && menu.findItem(R.id.action_Remove).isVisible()) { menu.findItem(R.id.action_Remove).setVisible(true); } else { menu.findItem(R.id.action_Remove).setVisible(false); } } } /* * Add record to list */ public void addToList() { if (type.equals(ListType.ANIME)) { animeRecord.setCreateFlag(true); animeRecord.setWatchedStatus(Anime.STATUS_WATCHING); animeRecord.setDirty(true); } else { mangaRecord.setCreateFlag(true); mangaRecord.setReadStatus(Manga.STATUS_READING); mangaRecord.setDirty(true); } setMenu(); setText(); } /* * Open the share dialog */ public void Share() { Intent sharingIntent = new Intent(android.content.Intent.ACTION_SEND); sharingIntent.setType("text/plain"); sharingIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET); sharingIntent.putExtra(Intent.EXTRA_TEXT, makeShareText()); startActivity(Intent.createChooser(sharingIntent, "Share via")); } @Override public void onPause() { super.onPause(); try { if (type.equals(ListType.ANIME)) { if (animeRecord.getDirty() && !animeRecord.getDeleteFlag()) { new WriteDetailTask(type, TaskJob.UPDATE, context, this).execute(animeRecord); } else if (animeRecord.getDeleteFlag()) { new WriteDetailTask(type, TaskJob.FORCESYNC, context, this).execute(animeRecord); } } else if (type.equals(ListType.MANGA)) { if (mangaRecord.getDirty() && !mangaRecord.getDeleteFlag()) { new WriteDetailTask(type, TaskJob.UPDATE, context, this).execute(mangaRecord); } else if (mangaRecord.getDeleteFlag()) { new WriteDetailTask(type, TaskJob.FORCESYNC, context, this).execute(mangaRecord); } } } catch (Exception e) { Log.e("MALX", "Error updating record: " + e.getMessage()); } } /* * Make the share text for the share dialog */ public String makeShareText() { String shareText = pref.getCustomShareText(); shareText = shareText.replace("$title;", getSupportActionBar().getTitle()); shareText = shareText.replace("$link;", "http://myanimelist.net/" + type.toString().toLowerCase(Locale.US) + "/" + Integer.toString(recordID)); shareText = shareText + getResources().getString(R.string.customShareText_fromAtarashii); return shareText; } /* * Get the records (Anime/Manga) */ public void getRecord() { if (MALApi.isNetworkAvailable(context)) { Bundle data = new Bundle(); data.putInt("recordID", recordID); new NetworkTask(TaskJob.GET, type, context, data, this, this).execute(); } else { setText(); swipeRefresh.setRefreshing(false); } } /* * Checks if this record is in our list */ public boolean isAdded() { if (ListType.ANIME.equals(type)) { if (animeRecord.getWatchedStatus() == null) { return false; } else { return true; } } else { if (mangaRecord.getReadStatus() == null) { return false; } else { return true; } } } /* * Show the EpisodePickerDialog */ @SuppressWarnings("deprecation") public void showEpisodesDialog() { FragmentManager fm = getSupportFragmentManager(); EpisodesPickerDialogFragment epdf = new EpisodesPickerDialogFragment(); epdf.show(fm, "fragment_EpisodePicker"); } /* * Show the MangaPickerDialog */ @SuppressWarnings("deprecation") public void showMangaDialog() { FragmentManager fm = getSupportFragmentManager(); MangaPickerDialogFragment mpdf = new MangaPickerDialogFragment(); mpdf.show(fm, "fragment_MangaProgress"); } /* * Show the RecordRemovalDialog */ public void showRemoveDialog() { FragmentManager fm = getSupportFragmentManager(); RemoveConfirmationDialogFragment rcdf = new RemoveConfirmationDialogFragment(); rcdf.show(fm, "fragment_RemoveConfirmation"); } /* * Show the StatusChangerDialog */ @SuppressWarnings("deprecation") public void showStatusDialog() { FragmentManager fm = getSupportFragmentManager(); StatusPickerDialogFragment spdf = new StatusPickerDialogFragment(); spdf.show(fm, "fragment_StatusPicker"); } /* * Episode picker dialog */ public void onDialogDismissed(int newValue) { if (newValue != animeRecord.getWatchedEpisodes()) { if (newValue == animeRecord.getEpisodes()) { animeRecord.setWatchedStatus(GenericRecord.STATUS_COMPLETED); } if (newValue == 0) { animeRecord.setWatchedStatus(Anime.STATUS_PLANTOWATCH); } animeRecord.setWatchedEpisodes(newValue); animeRecord.setDirty(true); setText(); setMenu(); } } @Override public void onResume() { super.onResume(); // received Android Beam? if (NfcAdapter.ACTION_NDEF_DISCOVERED.equals(getIntent().getAction())) processIntent(getIntent()); } @TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH) private void processIntent(Intent intent) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) { Parcelable[] rawMsgs = getIntent().getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES); // only one message sent during the beam NdefMessage msg = (NdefMessage) rawMsgs[0]; String message = new String(msg.getRecords()[0].getPayload()); String[] splitmessage = message.split(":", 2); if (splitmessage.length == 2) { try { type = ListType.valueOf(splitmessage[0].toUpperCase(Locale.US)); recordID = Integer.parseInt(splitmessage[1]); setCard(); getRecord(); } catch (NumberFormatException e) { finish(); } } } } @TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH) private void setupBeam() { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) { // setup beam functionality (if NFC is available) NfcAdapter mNfcAdapter = NfcAdapter.getDefaultAdapter(this); if (mNfcAdapter == null) { Log.i("MALX", "NFC not available"); } else { // Register NFC callback String message_str = type.toString() + ":" + String.valueOf(recordID); NdefMessage message = new NdefMessage(new NdefRecord[]{ new NdefRecord( NdefRecord.TNF_MIME_MEDIA, "application/net.somethingdreadful.MAL".getBytes(Charset.forName("US-ASCII")), new byte[0], message_str.getBytes(Charset.forName("US-ASCII"))), NdefRecord.createApplicationRecord(getPackageName()) }); mNfcAdapter.setNdefPushMessage(message, this); } } } @SuppressWarnings("unchecked") // Don't panic, we handle possible class cast exceptions @Override public void onNetworkTaskFinished(Object result, TaskJob job, ListType type, Bundle data, boolean cancelled) { try { if (type == ListType.ANIME) { animeRecord = (Anime) result; if (isAdded()) animeRecord.setDirty(true); } else { mangaRecord = (Manga) result; if (isAdded()) mangaRecord.setDirty(true); } setText(); swipeRefresh.setRefreshing(false); } catch (ClassCastException e) { Log.e("MALX", "error reading result because of invalid result class: " + result.getClass().toString()); Crouton.makeText(this, R.string.crouton_error_DetailsError, Style.ALERT).show(); } } @Override public void onNetworkTaskError(TaskJob job, ListType type, Bundle data, boolean cancelled) { Crouton.makeText(this, R.string.crouton_error_DetailsError, Style.ALERT).show(); } /* * Get the translation from strings.xml */ private String getStringFromResourceArray(int resArrayId, int notFoundStringId, int index) { Resources res = getResources(); try { String[] types = res.getStringArray(resArrayId); if (index < 0 || index >= types.length) // make sure to have a valid array index return res.getString(notFoundStringId); else return types[index]; } catch (Resources.NotFoundException e) { return res.getString(notFoundStringId); } } private String getAnimeTypeString(int typeInt) { return getStringFromResourceArray(R.array.mediaType_Anime, R.string.unknown, typeInt); } private String getAnimeStatusString(int statusInt) { return getStringFromResourceArray(R.array.mediaStatus_Anime, R.string.unknown, statusInt); } private String getMangaTypeString(int typeInt) { return getStringFromResourceArray(R.array.mediaType_Manga, R.string.unknown, typeInt); } private String getMangaStatusString(int statusInt) { return getStringFromResourceArray(R.array.mediaStatus_Manga, R.string.unknown, statusInt); } private String getUserStatusString(int statusInt) { return getStringFromResourceArray(R.array.mediaStatus_User, R.string.unknown, statusInt); } /* * Place all the text in the right textview */ public void setText() { if (type == null || (animeRecord == null && mangaRecord == null)) // not enough data to do anything return; GenericRecord record; setMenu(); TextView status = (TextView) findViewById(R.id.cardStatusLabel); TextView mediaType = (TextView) findViewById(R.id.mediaType); TextView mediaStatus = (TextView) findViewById(R.id.mediaStatus); if (type.equals(ListType.ANIME)) { record = animeRecord; Card statusCard = (Card) findViewById(R.id.status); if (animeRecord.getWatchedStatus() != null) { status.setText(WordUtils.capitalize(getUserStatusString(animeRecord.getWatchedStatusInt()))); statusCard.setVisibility(View.VISIBLE); } else { statusCard.setVisibility(View.GONE); } mediaType.setText(getAnimeTypeString(animeRecord.getTypeInt())); mediaStatus.setText(getAnimeStatusString(animeRecord.getStatusInt())); } else { record = mangaRecord; Card statusCard = (Card) findViewById(R.id.status); if (mangaRecord.getReadStatus() != null) { status.setText(WordUtils.capitalize(getUserStatusString(mangaRecord.getReadStatusInt()))); statusCard.setVisibility(View.VISIBLE); } else { statusCard.setVisibility(View.GONE); } mediaType.setText(getMangaTypeString(mangaRecord.getTypeInt())); mediaStatus.setText(getMangaStatusString(mangaRecord.getStatusInt())); } TextView synopsis = (TextView) findViewById(R.id.SynopsisContent); if (record.getSynopsis() == null) { if (MALApi.isNetworkAvailable(context)) { Bundle data = new Bundle(); data.putSerializable("record", type.equals(ListType.ANIME) ? animeRecord : mangaRecord); swipeRefresh.setRefreshing(true); new NetworkTask(TaskJob.GETDETAILS, type, context, data, this, this).execute(); } else { synopsis.setText(getString(R.string.crouton_error_noConnectivity)); } } else { synopsis.setMovementMethod(LinkMovementMethod.getInstance()); synopsis.setText(Html.fromHtml(record.getSynopsis())); } Card progress = (Card) findViewById(R.id.progress); if (isAdded()) { progress.setVisibility(View.VISIBLE); } else { progress.setVisibility(View.GONE); } if (type.equals(ListType.ANIME)) { TextView progresslabel1Current = (TextView) findViewById(R.id.progresslabel1Current); progresslabel1Current.setText(Integer.toString(animeRecord.getWatchedEpisodes())); TextView progresslabel1Total = (TextView) findViewById(R.id.progresslabel1Total); if (animeRecord.getEpisodes() == 0) progresslabel1Total.setText("/?"); else progresslabel1Total.setText("/" + Integer.toString(animeRecord.getEpisodes())); } else { TextView progresslabel1Current = (TextView) findViewById(R.id.progresslabel1Current); progresslabel1Current.setText(Integer.toString(mangaRecord.getVolumesRead())); TextView progresslabel1Total = (TextView) findViewById(R.id.progresslabel1Total); if (mangaRecord.getVolumes() == 0) progresslabel1Total.setText("/?"); else progresslabel1Total.setText("/" + Integer.toString(mangaRecord.getVolumes())); TextView progresslabel2Current = (TextView) findViewById(R.id.progresslabel2Current); progresslabel2Current.setText(Integer.toString(mangaRecord.getChaptersRead())); TextView progresslabel2Total = (TextView) findViewById(R.id.progresslabel2Total); if (mangaRecord.getChapters() == 0) progresslabel2Total.setText("/?"); else progresslabel2Total.setText("/" + Integer.toString(mangaRecord.getChapters())); } TextView MALScoreLabel = (TextView) findViewById(R.id.MALScoreLabel); RatingBar MALScoreBar = (RatingBar) findViewById(R.id.MALScoreBar); if (record.getMembersScore() == 0) { MALScoreBar.setVisibility(View.GONE); MALScoreLabel.setVisibility(View.GONE); } else { MALScoreBar.setVisibility(View.VISIBLE); MALScoreLabel.setVisibility(View.VISIBLE); MALScoreBar.setRating(record.getMembersScore() / 2); } RatingBar MyScoreBar = (RatingBar) findViewById(R.id.MyScoreBar); TextView MyScoreLabel = (TextView) findViewById(R.id.MyScoreLabel); if (isAdded()) { MyScoreLabel.setVisibility(View.VISIBLE); MyScoreBar.setVisibility(View.VISIBLE); MyScoreBar.setRating((float) record.getScore() / 2); } else { MyScoreLabel.setVisibility(View.GONE); MyScoreBar.setVisibility(View.GONE); } (findViewById(R.id.Image)).setLayoutParams(new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT)); Picasso.with(context) .load(record.getImageUrl()) .error(R.drawable.cover_error) .placeholder(R.drawable.cover_loading) .centerInside() .fit() .into((ImageView) findViewById(R.id.Image), new Callback() { @Override public void onSuccess() { ((Card) findViewById(R.id.detailCoverImage)).wrapWidth(false); } @Override public void onError() { } }); getSupportActionBar().setTitle(record.getTitle()); ((Card) findViewById(R.id.detailCoverImage)).Header.setText(record.getTitle()); setupBeam(); } @Override public void onRatingChanged(RatingBar ratingBar, float rating, boolean fromUser) { if (type.equals(ListType.ANIME)) { if (animeRecord != null) { animeRecord.setScore((int) (rating * 2)); animeRecord.setDirty(true); } } else { if (animeRecord != null) { mangaRecord.setScore((int) (rating * 2)); mangaRecord.setDirty(true); } } } public void onStatusDialogDismissed(String currentStatus) { if (type.equals(ListType.ANIME)) { if (Anime.STATUS_WATCHING.equals(currentStatus)) { animeRecord.setWatchedStatus(Anime.STATUS_WATCHING); } if (GenericRecord.STATUS_COMPLETED.equals(currentStatus)) { animeRecord.setWatchedStatus(Anime.STATUS_COMPLETED); if (animeRecord.getEpisodes() != 0) animeRecord.setWatchedEpisodes(animeRecord.getEpisodes()); } if (GenericRecord.STATUS_ONHOLD.equals(currentStatus)) { animeRecord.setWatchedStatus(Anime.STATUS_ONHOLD); } if (GenericRecord.STATUS_DROPPED.equals(currentStatus)) { animeRecord.setWatchedStatus(Anime.STATUS_DROPPED); } if ((Anime.STATUS_PLANTOWATCH.equals(currentStatus))) { animeRecord.setWatchedStatus(Anime.STATUS_PLANTOWATCH); } animeRecord.setDirty(true); } else { if (Manga.STATUS_READING.equals(currentStatus)) { mangaRecord.setReadStatus(Manga.STATUS_READING); } if (GenericRecord.STATUS_COMPLETED.equals(currentStatus)) { mangaRecord.setReadStatus(Manga.STATUS_COMPLETED); if (mangaRecord.getChapters() != 0) mangaRecord.setChaptersRead(mangaRecord.getChapters()); if (mangaRecord.getVolumes() != 0) mangaRecord.setVolumesRead(mangaRecord.getVolumes()); } if (GenericRecord.STATUS_ONHOLD.equals(currentStatus)) { mangaRecord.setReadStatus(Manga.STATUS_ONHOLD); } if (GenericRecord.STATUS_DROPPED.equals(currentStatus)) { mangaRecord.setReadStatus(Manga.STATUS_DROPPED); } if (Manga.STATUS_PLANTOREAD.equals(currentStatus)) { mangaRecord.setReadStatus(Manga.STATUS_PLANTOREAD); } mangaRecord.setDirty(true); } setText(); } public void onMangaDialogDismissed(int value, int value2) { if (value != mangaRecord.getChaptersRead()) { if (value == mangaRecord.getChapters() && mangaRecord.getChapters() != 0) { mangaRecord.setReadStatus(GenericRecord.STATUS_COMPLETED); } if (value == 0) { mangaRecord.setReadStatus(Manga.STATUS_PLANTOREAD); } mangaRecord.setChaptersRead(value); mangaRecord.setDirty(true); } if (value2 != mangaRecord.getVolumesRead()) { if (value2 == mangaRecord.getVolumes()) { mangaRecord.setReadStatus(GenericRecord.STATUS_COMPLETED); } if (value2 == 0) { mangaRecord.setReadStatus(Manga.STATUS_PLANTOREAD); } mangaRecord.setVolumesRead(value2); mangaRecord.setDirty(true); } if (value2 == 9001 || value == 9001) { Crouton.makeText(this, getString(R.string.crouton_info_Max_Counter), Style.INFO).show(); } setText(); setMenu(); } public void onRemoveConfirmed() { if (type.equals(ListType.ANIME)) { animeRecord.setDirty(true); animeRecord.setDeleteFlag(true); } else { mangaRecord.setDirty(true); mangaRecord.setDeleteFlag(true); } finish(); } @Override public void onCardClickListener(int res) { if (res == R.id.status) { showStatusDialog(); } else if (res == R.id.progress) { if (type.equals(ListType.ANIME)) { showEpisodesDialog(); } else { showMangaDialog(); } } } @Override public void onAPIAuthenticationError(ListType type, TaskJob job) { FragmentManager fm = getSupportFragmentManager(); UpdatePasswordDialogFragment passwordFragment = new UpdatePasswordDialogFragment(); passwordFragment.show(fm, "fragment_updatePassword"); } }
package com.spotify.netty.handler.codec.zmtp; import org.jboss.netty.buffer.ChannelBuffer; import org.jboss.netty.buffer.ChannelBuffers; /** * A ZMTP20Codec instance is a ChannelUpstreamHandler that, when placed in a ChannelPipeline, * will perform a ZMTP/2.0 handshake with the connected peer and replace itself with the proper * pipeline components to encode and decode ZMTP frames. */ public class ZMTP20Codec extends CodecBase { private final boolean interop; private boolean splitHandshake; /** * Construct a ZMTP20Codec with the specified session and optional interoperability behavior. * @param session the session that configures this codec * @param interop whether this socket should implement the ZMTP/1.0 interoperability handshake */ public ZMTP20Codec(ZMTPSession session, boolean interop) { super(session); this.interop = interop; } protected ChannelBuffer onConnect() { if (interop) { return makeZMTP2CompatSignature(); } else { return makeZMTP2Greeting(true); } } protected ChannelBuffer inputOutput(final ChannelBuffer buffer) throws ZMTPException { if (splitHandshake) { done(2, parseZMTP2Greeting(buffer, false)); return null; } if (interop) { buffer.markReaderIndex(); int version = detectProtocolVersion(buffer); if (version == 1) { buffer.resetReaderIndex(); done(version, ZMTP10Codec.readZMTP1RemoteIdentity(buffer)); // when a ZMTP/1.0 peer is detected, just send the identity bytes. Together // with the compatibility signature it makes for a valid ZMTP/1.0 greeting. return ChannelBuffers.wrappedBuffer(session.getLocalIdentity()); } else { splitHandshake = true; return makeZMTP2Greeting(false); } } else { done(2, parseZMTP2Greeting(buffer, true)); } return null; } private void done(int version, byte[] remoteIdentity) { if (listener != null) { listener.handshakeDone(version, remoteIdentity); } } /** * Read enough bytes from buffer to deduce the remote protocol version. If the protocol * version is determined to be ZMTP/1.0, reset the buffer to the beginning of buffer. If * version is determined to be a later version, the buffer is not reset. * * @param buffer the buffer of data to determine version from * @return false if not enough data is available, else true * @throws IndexOutOfBoundsException if there are not enough data available in buffer */ static int detectProtocolVersion(final ChannelBuffer buffer) { if (buffer.readByte() != (byte)0xff) { return 1; } buffer.skipBytes(8); if ((buffer.readByte() & 0x01) == 0) { return 1; } return 2; } /** * Make a ChannelBuffer containing a ZMTP/2.0 greeting, possibly leaving out the 10 initial * signature octets if includeSignature is false. * * @param includeSignature true if a full greeting should be sent, false if the initial 10 * octets should be left out * @return a ChannelBuffer containing the greeting */ private ChannelBuffer makeZMTP2Greeting(boolean includeSignature) { ChannelBuffer out = ChannelBuffers.dynamicBuffer(); if (includeSignature) { ZMTPUtils.encodeLength(0, out, true); // last byte of signature out.writeByte(0x7f); // protocol revision } out.writeByte(0x01); // socket-type out.writeByte(session.getSocketType().ordinal()); // identity // the final-short flag octet out.writeByte(0x00); out.writeByte(session.getLocalIdentity().length); out.writeBytes(session.getLocalIdentity()); return out; } private ChannelBuffer makeZMTP2CompatSignature() { ChannelBuffer out = ChannelBuffers.dynamicBuffer(); ZMTPUtils.encodeLength(session.getLocalIdentity().length + 1, out, true); out.writeByte(0x7f); return out; } static byte[] parseZMTP2Greeting(ChannelBuffer buffer, boolean expectSignature) throws ZMTPException { if (expectSignature) { if (buffer.readByte() != (byte)0xff) { throw new ZMTPException("Illegal ZMTP/2.0 greeting, first octet not 0xff"); } buffer.skipBytes(9); } // ignoring version number and socket type for now buffer.skipBytes(2); int val = buffer.readByte(); if (val != 0x00) { String s = String.format("Malformed greeting. Byte 13 expected to be 0x00, was: 0x%02x", val); throw new ZMTPException(s); } int len = buffer.readByte(); final byte[] identity = new byte[len]; buffer.readBytes(identity); return identity; } }
package com.sybit.education.taschengeldboerse.domain; import java.io.Serializable; import java.util.Objects; import javax.persistence.Basic; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Table; /** * * @author sat */ @Entity @Table(name = "jobs") public class Job implements Serializable { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Basic(optional = false) @Column(name = "id") private Integer id; @Column(name = "bezeichnung") private String bezeichnung; @Column(name = "anbieter") private Integer anbieter; @Column(name = "datum") private String datum; @Column(name = "uhrzeit") private String uhrzeit; @Column(name = "zeitaufwand") private String zeitaufwand; @Column(name = "turnus") private boolean turnus; @Column(name = "anforderungen") private String anforderungen; @Column(name = "zusaetzliche_infos") private String zusaetzliche_infos; @Column(name = "entlohnung") private String entlohnung; public Job() { } public Job(String bezeichnung, Integer Anbieter) { this.bezeichnung = bezeichnung; this.anbieter = Anbieter; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getBezeichnung() { return bezeichnung; } public void setBezeichnung(String Bezeichnung) { this.bezeichnung = Bezeichnung; } public Integer getAnbieter() { return anbieter; } public void setAnbieter(Integer Anbieter) { this.anbieter = Anbieter; } public String getDatum() { return datum; } public void setDatum(String datum) { this.datum = datum; } public String getUhrzeit() { return uhrzeit; } public void setUhrzeit(String uhrzeit) { this.uhrzeit = uhrzeit; } public String getZeitaufwand() { return zeitaufwand; } public void setZeitaufwand(String zeitaufwand) { this.zeitaufwand = zeitaufwand; } public boolean getTurnus() { return turnus; } public void setTurnus(boolean turnus) { this.turnus = turnus; } public String getAnforderungen() { return anforderungen; } public void setAnforderungen(String anforderungen) { this.anforderungen = anforderungen; } public void setZusaetzliche_infos(String zusaetzliche_infos) { this.zusaetzliche_infos = zusaetzliche_infos; } public String getZusaetzliche_infos() { return zusaetzliche_infos; } public String getEntlohnung() { return entlohnung; } public void setEntlohnung(String entlohnung) { this.entlohnung = entlohnung; } @Override public int hashCode() { int hash = 5; hash = 17 * hash + Objects.hashCode(this.id); hash = 17 * hash + Objects.hashCode(this.bezeichnung); hash = 17 * hash + Objects.hashCode(this.anbieter); hash = 17 * hash + Objects.hashCode(this.datum); hash = 17 * hash + Objects.hashCode(this.uhrzeit); hash = 17 * hash + Objects.hashCode(this.zeitaufwand); hash = 17 * hash + Objects.hashCode(this.turnus); hash = 17 * hash + Objects.hashCode(this.anforderungen); hash = 17 * hash + Objects.hashCode(this.zusaetzliche_infos); hash = 17 * hash + Objects.hashCode(this.entlohnung); return hash; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final Job other = (Job) obj; if (!Objects.equals(this.bezeichnung, other.bezeichnung)) { return false; } if (!Objects.equals(this.id, other.id)) { return false; } if (!Objects.equals(this.anbieter, other.anbieter)) { return false; } if (!Objects.equals(this.datum, other.datum)) { return false; } if (!Objects.equals(this.uhrzeit, other.uhrzeit)) { return false; } if (!Objects.equals(this.turnus, other.turnus)) { return false; } if (!Objects.equals(this.anforderungen, other.anforderungen)) { return false; } if (!Objects.equals(this.zusaetzliche_infos, other.zusaetzliche_infos)) { return false; } if (!Objects.equals(this.entlohnung, other.entlohnung)) { return false; } return true; } }
package com.thedeanda.ajaxproxy.ui.update; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.apache.commons.lang3.StringUtils; public class ReleaseVersion implements Comparable<ReleaseVersion> { private int major; private int minor; private int patch; private String input; public ReleaseVersion(int major, int minor, int patch) { this.major = major; this.minor = minor; this.patch = patch; } public ReleaseVersion(String version) { input = version; if (StringUtils.endsWith(version, "-SNAPSHOT")) { version = version.substring(0, version.length() - 9); } if (!StringUtils.isEmpty(version)) return; Pattern reg = Pattern.compile("(\\d+)(\\.(\\d+)(\\.(\\d+)(-SNAPSHOT)?)?)?"); Matcher matcher = reg.matcher(version); if (!matcher.matches()) return; major = parse(matcher.group(1)); minor = parse(matcher.group(3)); patch = parse(matcher.group(5)); } private int parse(String input) { if (StringUtils.isBlank(input)) return 0; return Integer.parseInt(input); } @Override public int compareTo(ReleaseVersion rv) { if (major < rv.major) return -1; else if (rv.major < major) return 1; if (minor < rv.minor) return -1; else if (rv.minor < minor) return 1; if (patch < rv.patch) return -1; else if (rv.patch < patch) return 1; return 0; } public int getMajor() { return major; } public int getMinor() { return minor; } public int getPatch() { return patch; } public String toString() { if (!StringUtils.isBlank(input)) { return input; } else { return String.format("%d.%d.%d", major, minor, patch); } } }
// Getdown - application installer, patcher and launcher // provided that the following conditions are met: // with the distribution. // THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, // INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A // PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, // INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED // TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT // LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. package com.threerings.getdown.util; /** * Accumulates the progress from a number of elements into a single * smoothly progressing progress. */ public class MetaProgressObserver implements ProgressObserver { public MetaProgressObserver (ProgressObserver target, long totalSize) { _target = target; _totalSize = totalSize; } public void startElement (long elementSize) { // add the previous size _accum += (_elementSize * 100); // then set the new one _elementSize = elementSize; } // documentation inherited from interface public void progress (int percent) { if (_totalSize > 0) { _target.progress((int)((_accum + (percent * _elementSize)) / _totalSize)); } } protected ProgressObserver _target; protected long _totalSize, _accum, _elementSize; }
package org.voltdb.rejoin; import java.io.File; import java.util.ArrayList; import java.util.LinkedList; import java.util.List; import java.util.Queue; import org.voltcore.logging.VoltLogger; import org.voltcore.messaging.HostMessenger; import org.voltcore.messaging.VoltMessage; import org.voltcore.utils.CoreUtils; import org.voltdb.VoltDB; import org.voltdb.messaging.RejoinMessage; import org.voltdb.messaging.RejoinMessage.Type; import org.voltdb.utils.VoltFile; /** * Sequentially rejoins each site. This rejoin coordinator is accessed by sites * sequentially, so no need to synchronize. */ public class SequentialRejoinCoordinator extends RejoinCoordinator { private static final VoltLogger rejoinLog = new VoltLogger("REJOIN"); // contains all sites that haven't started streaming snapshot private final Queue<Long> m_pendingSites; // contains all sites that haven't finished replaying transactions private final Queue<Long> m_rejoiningSites = new LinkedList<Long>(); public SequentialRejoinCoordinator(HostMessenger messenger, List<Long> sites, String voltroot) { super(messenger); m_pendingSites = new LinkedList<Long>(sites); if (m_pendingSites.isEmpty()) { VoltDB.crashLocalVoltDB("No execution sites to rejoin", false, null); } // clear overflow dir in case there are files left from previous runs try { File overflowDir = new File(voltroot, "rejoin_overflow"); if (overflowDir.exists()) { VoltFile.recursivelyDelete(overflowDir); } } catch (Exception e) { VoltDB.crashLocalVoltDB("Fail to clear rejoin overflow directory", false, e); } } /** * Send rejoin initiation message to the local site * @param HSId */ private void initiateRejoinOnSite(long HSId) { RejoinMessage msg = new RejoinMessage(getHSId(), RejoinMessage.Type.INITIATION); send(HSId, msg); } @Override public void startRejoin() { long firstSite = m_pendingSites.poll(); m_rejoiningSites.add(firstSite); String HSIdString = CoreUtils.hsIdToString(firstSite); rejoinLog.debug("Start rejoining site " + HSIdString); initiateRejoinOnSite(firstSite); } private void onSnapshotStreamFinished(long HSId) { rejoinLog.info("Finished streaming snapshot to site " + CoreUtils.hsIdToString(HSId)); if (!m_pendingSites.isEmpty()) { long nextSite = m_pendingSites.poll(); m_rejoiningSites.add(nextSite); String HSIdString = CoreUtils.hsIdToString(nextSite); rejoinLog.debug("Start rejoining site " + HSIdString); initiateRejoinOnSite(nextSite); } } private void onReplayFinished(long HSId) { if (!m_rejoiningSites.remove(HSId)) { VoltDB.crashLocalVoltDB("Unknown site " + CoreUtils.hsIdToString(HSId) + " finished rejoin", false, null); } String msg = "Finished rejoining site " + CoreUtils.hsIdToString(HSId); ArrayList<Long> remainingSites = new ArrayList<Long>(m_pendingSites); remainingSites.addAll(m_rejoiningSites); if (!remainingSites.isEmpty()) { msg += ". Remaining sites to rejoin: " + CoreUtils.hsIdCollectionToString(remainingSites); } else { msg += ". All sites completed rejoin."; } rejoinLog.info(msg); if (m_rejoiningSites.isEmpty()) { // no more sites to rejoin, we're done VoltDB.instance().onExecutionSiteRejoinCompletion(0l); } } @Override public void deliver(VoltMessage message) { if (!(message instanceof RejoinMessage)) { VoltDB.crashLocalVoltDB("Unknown message type " + message.getClass().toString() + " sent to the rejoin coordinator", false, null); } RejoinMessage rm = (RejoinMessage) message; Type type = rm.getType(); if (type == RejoinMessage.Type.SNAPSHOT_FINISHED) { onSnapshotStreamFinished(rm.m_sourceHSId); } else if (type == RejoinMessage.Type.REPLAY_FINISHED) { onReplayFinished(rm.m_sourceHSId); } else { VoltDB.crashLocalVoltDB("Wrong rejoin message of type " + type + " sent to the rejoin coordinator", false, null); } } }
package de.epiceric.shopchest.listeners; import de.epiceric.shopchest.ShopChest; import de.epiceric.shopchest.config.Config; import de.epiceric.shopchest.shop.Shop; import me.wiefferink.areashop.events.notify.DeletedRegionEvent; import me.wiefferink.areashop.events.notify.ResoldRegionEvent; import me.wiefferink.areashop.events.notify.SoldRegionEvent; import me.wiefferink.areashop.events.notify.UnrentedRegionEvent; import me.wiefferink.areashop.regions.GeneralRegion; import org.bukkit.event.EventHandler; import org.bukkit.event.Listener; import org.codemc.worldguardwrapper.WorldGuardWrapper; import org.codemc.worldguardwrapper.region.IWrappedRegion; public class AreaShopListener implements Listener { private ShopChest plugin; public AreaShopListener(ShopChest plugin) { this.plugin = plugin; } @EventHandler public void onRegionDeleted(DeletedRegionEvent e) { if (Config.enableAreaShopIntegration && Config.areashopRemoveShopEvents.contains("DELETE")) { removeShopsInRegion(e.getRegion()); } } @EventHandler public void onRegionUnrented(UnrentedRegionEvent e) { if (Config.enableAreaShopIntegration && Config.areashopRemoveShopEvents.contains("UNRENT")) { removeShopsInRegion(e.getRegion()); } } @EventHandler public void onRegionResold(ResoldRegionEvent e) { if (Config.enableAreaShopIntegration && Config.areashopRemoveShopEvents.contains("RESELL")) { removeShopsInRegion(e.getRegion()); } } @EventHandler public void onRegionSold(SoldRegionEvent e) { if (Config.enableAreaShopIntegration && Config.areashopRemoveShopEvents.contains("SELL")) { removeShopsInRegion(e.getRegion()); } } private void removeShopsInRegion(GeneralRegion generalRegion) { if (!plugin.hasWorldGuard()) return; for (Shop shop : plugin.getShopUtils().getShopsCopy()) { if (!shop.getLocation().getWorld().getName().equals(generalRegion.getWorldName())) continue; for (IWrappedRegion r : WorldGuardWrapper.getInstance().getRegions(shop.getLocation())) { if (generalRegion.getLowerCaseName().equals(r.getId())) { plugin.getShopUtils().removeShop(shop, true); break; } } } } }
package com.indeed.util.mmap; import com.google.common.annotations.VisibleForTesting; import com.google.common.io.Closeables; import java.io.File; import java.io.FileDescriptor; import java.io.FileNotFoundException; import java.io.IOException; import java.io.RandomAccessFile; import java.lang.reflect.Field; import java.nio.ByteOrder; import java.nio.channels.FileChannel; /** * @author jplaisance */ public final class MMapBuffer implements BufferResource { private static final Field FD_FIELD; public static final int PAGE_SIZE = 4096; private static final int READ_ONLY = 0; static final int READ_WRITE = 1; static final long MAP_FAILED = -1L; static final int MAP_SHARED = 1; static final int MAP_PRIVATE = 2; static final int MAP_ANONYMOUS = 4; static { LoadIndeedMMap.loadLibrary(); try { FD_FIELD = FileDescriptor.class.getDeclaredField("fd"); FD_FIELD.setAccessible(true); } catch (NoSuchFieldException e) { throw new RuntimeException(e); } } private final long address; private final DirectMemory memory; private static RandomAccessFile open(File file, FileChannel.MapMode mapMode) throws FileNotFoundException { if (!file.exists() && mapMode == FileChannel.MapMode.READ_ONLY) { throw new FileNotFoundException(file + " does not exist"); } final String openMode; if (mapMode == FileChannel.MapMode.READ_ONLY) { openMode = "r"; } else if (mapMode == FileChannel.MapMode.READ_WRITE) { openMode = "rw"; } else { throw new IllegalArgumentException("only MapMode.READ_ONLY and MapMode.READ_WRITE are supported"); } return new RandomAccessFile(file, openMode); } public MMapBuffer(File file, FileChannel.MapMode mapMode, ByteOrder order) throws IOException { this(file, 0, file.length(), mapMode, order); } public MMapBuffer(File file, long offset, long length, FileChannel.MapMode mapMode, ByteOrder order) throws IOException { this(open(file, mapMode), file, offset, length, mapMode, order, true); } public MMapBuffer(RandomAccessFile raf, File file, long offset, long length, FileChannel.MapMode mapMode, ByteOrder order) throws IOException { this(raf, file, offset, length, mapMode, order, false); } public MMapBuffer(RandomAccessFile raf, File file, long offset, long length, FileChannel.MapMode mapMode, ByteOrder order, boolean closeFile) throws IOException { try { if (offset < 0) throw new IllegalArgumentException("error mapping [" + file + "]: offset must be >= 0"); if (length <= 0) { if (length < 0) throw new IllegalArgumentException("error mapping [" + file + "]: length must be >= 0"); address = 0; memory = new DirectMemory(0, 0, order); } else { final int prot; if (mapMode == FileChannel.MapMode.READ_ONLY) { prot = READ_ONLY; } else if (mapMode == FileChannel.MapMode.READ_WRITE) { prot = READ_WRITE; } else { throw new IllegalArgumentException("only MapMode.READ_ONLY and MapMode.READ_WRITE are supported"); } if (raf.length() < offset+length) { if (mapMode == FileChannel.MapMode.READ_WRITE) { raf.setLength(offset+length); } else { throw new IllegalArgumentException("cannot open file [" + file + "] in read only mode with offset+length > file.length()"); } } final int fd; try { fd = FD_FIELD.getInt(raf.getFD()); } catch (IllegalAccessException e) { throw new RuntimeException(e); } address = mmap(length, prot, MAP_SHARED, fd, offset); if (address == MAP_FAILED) { final int errno = errno(); throw new IOException("mmap(" + file.getAbsolutePath() + ", " + offset + ", " + length + ", " + mapMode + ") failed [Errno " + errno + "]"); } memory = new DirectMemory(address, length, order); } } finally { if (closeFile) { Closeables.close(raf, true); } } } static native long mmap(long length, int prot, int flags, int fd, long offset); static native int munmap(long address, long length); static native long mremap(long address, long oldLength, long newLength); private static native int msync(long address, long length); private static native int madvise(long address, long length); static native int errno(); //this is not particularly useful, the syscall takes forever public void advise(long position, long length) throws IOException { final long ap = address+position; final long a = (ap)/PAGE_SIZE*PAGE_SIZE; final long l = Math.min(length+(ap-a), address+memory.length()-ap); final int err = madvise(a, l); if (err != 0) { throw new IOException("madvise failed with error code: "+err); } } public void sync(long position, long length) throws IOException { final long ap = address+position; final long a = (ap)/PAGE_SIZE*PAGE_SIZE; final long l = Math.min(length+(ap-a), address+memory.length()-ap); final int err = msync(a, l); if (err != 0) { throw new IOException("msync failed with error code: "+err); } } public void mlock(long position, long length) { if (position < 0) throw new IndexOutOfBoundsException(); if (length < 0) throw new IndexOutOfBoundsException(); if (position+length > memory.length()) throw new IndexOutOfBoundsException(); NativeMemoryUtils.mlock(address+position, length); } public void munlock(long position, long length) { if (position < 0) throw new IndexOutOfBoundsException(); if (length < 0) throw new IndexOutOfBoundsException(); if (position+length > memory.length()) throw new IndexOutOfBoundsException(); NativeMemoryUtils.munlock(address+position, length); } public void mincore(long position, long length, DirectMemory direct) { if (position+length > memory().length()) { throw new IndexOutOfBoundsException(); } final long ap = address+position; final long a = ap/PAGE_SIZE*PAGE_SIZE; final long l = length+(ap-a); if ((l+PAGE_SIZE-1)/PAGE_SIZE > direct.length()) throw new IndexOutOfBoundsException(); NativeMemoryUtils.mincore(a, l, direct); } @VisibleForTesting int getErrno() { return errno(); } @Override public void close() throws IOException { //hack to deal with 0 byte files if (address != 0) { if (munmap(address, memory.length()) != 0) throw new IOException("munmap failed [Errno " + errno() + "]"); } } public DirectMemory memory() { return memory; } }
package edu.isi.karma.view.tableheadings; import static edu.isi.karma.controller.update.WorksheetHierarchicalHeadersUpdate.JsonKeys.cells; import java.util.LinkedList; import java.util.List; import org.json.JSONException; import org.json.JSONWriter; import edu.isi.karma.view.VWorksheet; import edu.isi.karma.view.VWorkspace; ; /** * Contains the levels of headings, except for the root of the tree. * * @author szekely * */ public class VHTreeNodeLevel { private final List<VHTreeNode> elements = new LinkedList<VHTreeNode>(); private final int depth; VHTreeNodeLevel(int depth) { super(); this.depth = depth; } VHTreeNodeLevel(VHTreeNode root) { super(); this.elements.add(root); this.depth = 0; } int getDepth() { return depth; } boolean isFinalLevel() { for (VHTreeNode n : elements) { if (n.hasChildren()) { return false; } } return true; } VHTreeNodeLevel getNextLevel() { VHTreeNodeLevel nextLevel = new VHTreeNodeLevel(depth + 1); for (VHTreeNode n : elements) { if (n.hasChildren()) { nextLevel.elements.addAll(n.getChildren()); } else { nextLevel.elements.add(n); } } return nextLevel; } void generateJson(JSONWriter jw, VWorksheet vWorksheet, VWorkspace vWorkspace) throws JSONException { jw.object() .key(cells.name()).array(); for (VHTreeNode n : elements) { n.generateJson(jw, depth, vWorksheet, vWorkspace); } jw.endArray(); jw.endObject(); } }
package io.branch.referral; import android.annotation.SuppressLint; import android.app.Dialog; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.pm.PackageManager; import android.content.pm.ResolveInfo; import android.graphics.Color; import android.graphics.drawable.ColorDrawable; import android.graphics.drawable.Drawable; import android.os.Build; import android.text.TextUtils; import android.view.Gravity; import android.view.KeyEvent; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.BaseAdapter; import android.widget.ListView; import android.widget.TextView; import android.widget.Toast; import java.util.ArrayList; import java.util.List; /** * <p>Class that provides a chooser dialog with customised share options to share a link. * Class provides customised and easy way of sharing a deep link with other applications. </p> */ class ShareLinkManager { /* The custom chooser dialog for selecting an application to share the link. */ AnimatedDialog shareDlg_; Branch.BranchLinkShareListener callback_; Branch.IChannelProperties channelPropertiesCallback_; /* List of apps available for sharing. */ private List<ResolveInfo> appList_; /* Intent for sharing with selected application.*/ private Intent shareLinkIntent_; /* Background color for the list view in enabled state. */ private final int BG_COLOR_ENABLED = Color.argb(60, 17, 4, 56); /* Background color for the list view in disabled state. */ private final int BG_COLOR_DISABLED = Color.argb(20, 17, 4, 56); /* Current activity context.*/ Context context_; /* Default height for the list item.*/ private static int viewItemMinHeight_ = 100; /* Default icon height size multiplier*/ private static int ICON_SIZER = 2; /* Indicates whether a sharing is in progress*/ private boolean isShareInProgress_ = false; /* Styleable resource for share sheet.*/ private int shareDialogThemeID_ = -1; /* Size of app icons in share sheet */ private int iconSize_ = 50; private Branch.ShareLinkBuilder builder_; final int padding = 5; final int leftMargin = 100; private List<String> includeInShareSheet = new ArrayList<>(); private List<String> excludeFromShareSheet = new ArrayList<>(); /** * Creates an application selector and shares a link on user selecting the application. * * @param builder A {@link io.branch.referral.Branch.ShareLinkBuilder} instance to build share link. * @return Instance of the {@link Dialog} holding the share view. Null if sharing dialog is not created due to any error. */ public Dialog shareLink(Branch.ShareLinkBuilder builder) { builder_ = builder; context_ = builder.getActivity(); callback_ = builder.getCallback(); channelPropertiesCallback_ = builder.getChannelPropertiesCallback(); shareLinkIntent_ = new Intent(Intent.ACTION_SEND); shareLinkIntent_.setType("text/plain"); shareDialogThemeID_ = builder.getStyleResourceID(); includeInShareSheet = builder.getIncludedInShareSheet(); excludeFromShareSheet = builder.getExcludedFromShareSheet(); iconSize_ = builder.getIconSize(); try { createShareDialog(builder.getPreferredOptions()); } catch (Exception e) { e.printStackTrace(); if (callback_ != null) { callback_.onLinkShareResponse(null, null, new BranchError("Trouble sharing link", BranchError.ERR_BRANCH_NO_SHARE_OPTION)); } else { PrefHelper.Debug("Unable create share options. Couldn't find applications on device to share the link."); } } return shareDlg_; } /** * Dismiss the share dialog if showing. Should be called on activity stopping. * * @param animateClose A {@link Boolean} to specify whether to close the dialog with an animation. * A value of true will close the dialog with an animation. Setting this value * to false will close the Dialog immediately. */ public void cancelShareLinkDialog(boolean animateClose) { if (shareDlg_ != null && shareDlg_.isShowing()) { if (animateClose) { // Cancel the dialog with animation shareDlg_.cancel(); } else { // Dismiss the dialog immediately shareDlg_.dismiss(); } } } /** * Create a custom chooser dialog with available share options. * * @param preferredOptions List of {@link io.branch.referral.SharingHelper.SHARE_WITH} options. */ private void createShareDialog(List<SharingHelper.SHARE_WITH> preferredOptions) { final PackageManager packageManager = context_.getPackageManager(); final List<ResolveInfo> preferredApps = new ArrayList<>(); final List<ResolveInfo> matchingApps = packageManager.queryIntentActivities(shareLinkIntent_, PackageManager.MATCH_DEFAULT_ONLY); List<ResolveInfo> cleanedMatchingApps = new ArrayList<>(); final List<ResolveInfo> cleanedMatchingAppsFinal = new ArrayList<>(); ArrayList<SharingHelper.SHARE_WITH> packagesFilterList = new ArrayList<>(preferredOptions); /* Get all apps available for sharing and the available preferred apps. */ for (ResolveInfo resolveInfo : matchingApps) { SharingHelper.SHARE_WITH foundMatching = null; String packageName = resolveInfo.activityInfo.packageName; for (SharingHelper.SHARE_WITH PackageFilter : packagesFilterList) { if (resolveInfo.activityInfo != null && packageName.toLowerCase().contains(PackageFilter.toString().toLowerCase())) { foundMatching = PackageFilter; break; } } if (foundMatching != null) { preferredApps.add(resolveInfo); preferredOptions.remove(foundMatching); } } /* Create all app list with copy link item. */ matchingApps.removeAll(preferredApps); matchingApps.addAll(0, preferredApps); //if apps are explicitly being included, add only those, otherwise at the else statement add them all if (includeInShareSheet.size() > 0) { for (ResolveInfo r : matchingApps) { if (includeInShareSheet.contains(r.activityInfo.packageName)) { cleanedMatchingApps.add(r); } } } else { cleanedMatchingApps = matchingApps; } //does our list contain explicitly excluded items? do not carry them into the next list for (ResolveInfo r : cleanedMatchingApps) { if (!excludeFromShareSheet.contains(r.activityInfo.packageName)) { cleanedMatchingAppsFinal.add(r); } } //make sure our "show more" option includes preferred apps for (ResolveInfo r : matchingApps) { for (SharingHelper.SHARE_WITH shareWith : packagesFilterList) if (shareWith.toString().equalsIgnoreCase(r.activityInfo.packageName)) { cleanedMatchingAppsFinal.add(r); } } cleanedMatchingAppsFinal.add(new CopyLinkItem()); matchingApps.add(new CopyLinkItem()); preferredApps.add(new CopyLinkItem()); if (preferredApps.size() > 1) { /* Add more and copy link option to preferred app.*/ if (matchingApps.size() > preferredApps.size()) { preferredApps.add(new MoreShareItem()); } appList_ = preferredApps; } else { appList_ = cleanedMatchingAppsFinal; } /* Copy link option will be always there for sharing. */ final ChooserArrayAdapter adapter = new ChooserArrayAdapter(); final ListView shareOptionListView; if (shareDialogThemeID_ > 1 && Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { shareOptionListView = new ListView(context_, null, 0, shareDialogThemeID_); } else { shareOptionListView = new ListView(context_); } shareOptionListView.setHorizontalFadingEdgeEnabled(false); shareOptionListView.setBackgroundColor(Color.WHITE); shareOptionListView.setSelector(new ColorDrawable(Color.TRANSPARENT)); if (builder_.getSharingTitleView() != null) { shareOptionListView.addHeaderView(builder_.getSharingTitleView(), null, false); } else if (!TextUtils.isEmpty(builder_.getSharingTitle())) { TextView textView = new TextView(context_); textView.setText(builder_.getSharingTitle()); textView.setBackgroundColor(BG_COLOR_DISABLED); textView.setTextColor(BG_COLOR_DISABLED); textView.setTextAppearance(context_, android.R.style.TextAppearance_Medium); textView.setTextColor(context_.getResources().getColor(android.R.color.darker_gray)); textView.setPadding(leftMargin, padding, padding, padding); shareOptionListView.addHeaderView(textView, null, false); } shareOptionListView.setAdapter(adapter); if (builder_.getDividerHeight() >= 0) { //User set height shareOptionListView.setDividerHeight(builder_.getDividerHeight()); } else if (builder_.getIsFullWidthStyle()) { shareOptionListView.setDividerHeight(0); // Default no divider for full width dialog } shareOptionListView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> adapterView, View view, int pos, long l) { if (view == null) return; if (view.getTag() instanceof MoreShareItem) { appList_ = cleanedMatchingAppsFinal; adapter.notifyDataSetChanged(); } else if (view.getTag() instanceof ResolveInfo) { ResolveInfo resolveInfo = (ResolveInfo) view.getTag(); if (callback_ != null) { String selectedChannelName = ""; if (context_ != null && resolveInfo.loadLabel(context_.getPackageManager()) != null) { selectedChannelName = resolveInfo.loadLabel(context_.getPackageManager()).toString(); } builder_.getShortLinkBuilder().setChannel(resolveInfo.loadLabel(context_.getPackageManager()).toString()); callback_.onChannelSelected(selectedChannelName); } adapter.selectedPos = pos - shareOptionListView.getHeaderViewsCount(); adapter.notifyDataSetChanged(); invokeSharingClient(resolveInfo); if (shareDlg_ != null) { shareDlg_.cancel(); } } } }); if (builder_.getDialogThemeResourceID() > 0) { shareDlg_ = new AnimatedDialog(context_, builder_.getDialogThemeResourceID()); } else { shareDlg_ = new AnimatedDialog(context_, builder_.getIsFullWidthStyle()); } shareDlg_.setContentView(shareOptionListView); shareDlg_.show(); if (callback_ != null) { callback_.onShareLinkDialogLaunched(); } shareDlg_.setOnDismissListener(new DialogInterface.OnDismissListener() { @Override public void onDismiss(DialogInterface dialogInterface) { if (callback_ != null) { callback_.onShareLinkDialogDismissed(); callback_ = null; } // Release context to prevent leaks if (!isShareInProgress_) { context_ = null; builder_ = null; } shareDlg_ = null; } }); shareDlg_.setOnKeyListener(new DialogInterface.OnKeyListener() { @Override public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) { if (event.getAction() != KeyEvent.ACTION_UP) return false; boolean handled = false; switch (keyCode){ case KeyEvent.KEYCODE_ENTER: case KeyEvent.KEYCODE_DPAD_CENTER: if (adapter.selectedPos >= 0 && adapter.selectedPos < adapter.getCount()) { shareOptionListView.performItemClick( adapter.getView(adapter.selectedPos, null, null), adapter.selectedPos, shareOptionListView.getItemIdAtPosition(adapter.selectedPos)); } break; case KeyEvent.KEYCODE_BACK: shareDlg_.dismiss(); handled = true; break; case KeyEvent.KEYCODE_DPAD_DOWN: if (adapter.selectedPos < (adapter.getCount()-1)) { adapter.selectedPos++; adapter.notifyDataSetChanged(); } handled = true; break; case KeyEvent.KEYCODE_DPAD_UP: if (adapter.selectedPos > 0) { adapter.selectedPos adapter.notifyDataSetChanged(); } handled = true; break; } return handled; } }); } private void invokeSharingClient(final ResolveInfo selectedResolveInfo) { isShareInProgress_ = true; final String channelName = selectedResolveInfo.loadLabel(context_.getPackageManager()).toString(); BranchShortLinkBuilder shortLinkBuilder = builder_.getShortLinkBuilder(); shortLinkBuilder.generateShortUrlInternal(new Branch.BranchLinkCreateListener() { @Override public void onLinkCreate(String url, BranchError error) { if (error == null) { shareWithClient(selectedResolveInfo, url, channelName); } else { //If there is a default URL specified share it. String defaultUrl = builder_.getDefaultURL(); if (defaultUrl != null && defaultUrl.trim().length() > 0) { shareWithClient(selectedResolveInfo, defaultUrl, channelName); } else { if (callback_ != null) { callback_.onLinkShareResponse(url, channelName, error); } else { PrefHelper.Debug("Unable to share link " + error.getMessage()); } if (error.getErrorCode() == BranchError.ERR_BRANCH_NO_CONNECTIVITY || error.getErrorCode() == BranchError.ERR_BRANCH_TRACKING_DISABLED) { shareWithClient(selectedResolveInfo, url, channelName); } else { cancelShareLinkDialog(false); isShareInProgress_ = false; } } } } }, true); } private void shareWithClient(ResolveInfo selectedResolveInfo, String url, String channelName) { if (callback_ != null) { callback_.onLinkShareResponse(url, channelName, null); } else { PrefHelper.Debug("Shared link with " + channelName); } if (selectedResolveInfo instanceof CopyLinkItem) { addLinkToClipBoard(url, builder_.getShareMsg()); } else { shareLinkIntent_.setPackage(selectedResolveInfo.activityInfo.packageName); String shareSub = builder_.getShareSub(); String shareMsg = builder_.getShareMsg(); if (channelPropertiesCallback_ != null) { String customShareSub = channelPropertiesCallback_.getSharingTitleForChannel(channelName); String customShareMsg = channelPropertiesCallback_.getSharingMessageForChannel(channelName); if (!TextUtils.isEmpty(customShareSub)) { shareSub = customShareSub; } if (!TextUtils.isEmpty(customShareMsg)) { shareMsg = customShareMsg; } } if (shareSub != null && shareSub.trim().length() > 0) { shareLinkIntent_.putExtra(Intent.EXTRA_SUBJECT, shareSub); } shareLinkIntent_.putExtra(Intent.EXTRA_TEXT, shareMsg + "\n" + url); context_.startActivity(shareLinkIntent_); } } /** * Adds a given link to the clip board. * * @param url A {@link String} to add to the clip board * @param label A {@link String} label for the adding link */ @SuppressWarnings("deprecation") @SuppressLint("NewApi") private void addLinkToClipBoard(String url, String label) { int sdk = android.os.Build.VERSION.SDK_INT; if (sdk < android.os.Build.VERSION_CODES.HONEYCOMB) { android.text.ClipboardManager clipboard = (android.text.ClipboardManager) context_.getSystemService(Context.CLIPBOARD_SERVICE); clipboard.setText(url); } else { android.content.ClipboardManager clipboard = (android.content.ClipboardManager) context_.getSystemService(Context.CLIPBOARD_SERVICE); android.content.ClipData clip = android.content.ClipData.newPlainText(label, url); clipboard.setPrimaryClip(clip); } Toast.makeText(context_, builder_.getUrlCopiedMessage(), Toast.LENGTH_SHORT).show(); } /* * Adapter class for creating list of available share options */ private class ChooserArrayAdapter extends BaseAdapter { public int selectedPos = -1; @Override public int getCount() { return appList_.size(); } @Override public Object getItem(int position) { return appList_.get(position); } @Override public long getItemId(int position) { return position; } @Override public View getView(int position, View convertView, ViewGroup parent) { ShareItemView itemView; if (convertView == null) { itemView = new ShareItemView(context_); } else { itemView = (ShareItemView) convertView; } ResolveInfo resolveInfo = appList_.get(position); boolean setSelected = position == selectedPos; itemView.setLabel(resolveInfo.loadLabel(context_.getPackageManager()).toString(), resolveInfo.loadIcon(context_.getPackageManager()), setSelected); itemView.setTag(resolveInfo); return itemView; } @Override public boolean isEnabled(int position) { return selectedPos < 0; } } /** * Class for sharing item view to be displayed in the list with Application icon and Name. */ private class ShareItemView extends TextView { Context context_; int iconSizeDP_; public ShareItemView(Context context) { super(context); context_ = context; this.setPadding(leftMargin, padding, padding, padding); this.setGravity(Gravity.START | Gravity.CENTER_VERTICAL); this.setMinWidth(context_.getResources().getDisplayMetrics().widthPixels); this.iconSizeDP_ = iconSize_ != 0 ? BranchUtil.dpToPx(context, iconSize_) : 0; } public void setLabel(String appName, Drawable appIcon, boolean isEnabled) { this.setText("\t" + appName); this.setTag(appName); if (appIcon == null) { this.setTextAppearance(context_, android.R.style.TextAppearance_Large); this.setCompoundDrawablesWithIntrinsicBounds(null, null, null, null); } else { if (iconSizeDP_ != 0) { appIcon.setBounds(0, 0, iconSizeDP_, iconSizeDP_); this.setCompoundDrawables(appIcon, null, null, null); } else { this.setCompoundDrawablesWithIntrinsicBounds(appIcon, null, null, null); } this.setTextAppearance(context_, android.R.style.TextAppearance_Medium); viewItemMinHeight_ = Math.max(viewItemMinHeight_, appIcon.getCurrent().getBounds().centerY()*ICON_SIZER + padding); } this.setMinHeight(viewItemMinHeight_); this.setTextColor(context_.getResources().getColor(android.R.color.black)); if (isEnabled) { this.setBackgroundColor(BG_COLOR_ENABLED); } else { this.setBackgroundColor(BG_COLOR_DISABLED); } } } /** * Class for sharing item more */ private class MoreShareItem extends ResolveInfo { @SuppressWarnings("NullableProblems") @Override public CharSequence loadLabel(PackageManager pm) { return builder_.getMoreOptionText(); } @SuppressWarnings("NullableProblems") @Override public Drawable loadIcon(PackageManager pm) { return builder_.getMoreOptionIcon(); } } /** * Class for Sharing Item copy URl */ private class CopyLinkItem extends ResolveInfo { @SuppressWarnings("NullableProblems") @Override public CharSequence loadLabel(PackageManager pm) { return builder_.getCopyURlText(); } @SuppressWarnings("NullableProblems") @Override public Drawable loadIcon(PackageManager pm) { return builder_.getCopyUrlIcon(); } } }
package fr.insee.pogues.webservice.rest; import fr.insee.pogues.persistence.service.QuestionnairesService; import fr.insee.pogues.transforms.*; import io.swagger.annotations.*; import org.apache.commons.io.IOUtils; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.json.simple.JSONArray; import org.json.simple.JSONObject; import org.springframework.beans.factory.annotation.Autowired; import javax.servlet.http.HttpServletRequest; import javax.ws.rs.*; import javax.ws.rs.core.Context; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import javax.ws.rs.core.StreamingOutput; import java.io.ByteArrayInputStream; import java.io.InputStream; import java.net.URI; import java.nio.charset.StandardCharsets; import java.util.HashMap; import java.util.Map; /** * Main WebService class of the PoguesBOOrchestrator * * @author I6VWID */ @Path("/transform") @Api(value = "Pogues Transforms") public class PoguesTransforms { final static Logger logger = LogManager.getLogger(PoguesTransforms.class); @Autowired JSONToXML jsonToXML; @Autowired XMLToDDI xmlToDDI; @Autowired DDIToXForm ddiToXForm; @Autowired XFormToURI xformToUri; @Autowired QuestionnairesService questionnairesService; @POST @Path("visualize/{name}") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_XML) @ApiOperation( value = "Get visualization URI from JSON serialized Pogues entity", notes = "Name MUST refer to the name attribute owned by the nested DataCollectionObject" ) @ApiImplicitParams(value = { @ApiImplicitParam(name = "json body", value = "JSON representation of the Pogues Model", paramType = "body", dataType = "org.json.simple.JSONObject") }) public Response visualizeFromBody( @Context final HttpServletRequest request, @PathParam(value = "name") String name ) throws Exception { PipeLine pipeline = new PipeLine(); Map<String, Object> params = new HashMap<>(); params.put("name", name); try { StreamingOutput stream = output -> { try { output.write(pipeline .from(request.getInputStream()) .map(jsonToXML::transform, params) .map(xmlToDDI::transform, params) .map(ddiToXForm::transform, params) .map(xformToUri::transform, params) .transform() .getBytes()); } catch (Exception e) { logger.error(e.getMessage()); throw new PoguesException(500, e.getMessage(), null); } }; return Response.ok(stream).build(); } catch (Exception e) { e.printStackTrace(); throw e; } } @GET @Path("visualize/{id}") @ApiOperation( value = "Get visualization URI from JSON serialized Pogues entity", notes = "Retrieves entity in datastore before pass it through the transformation pipeline" ) public Response visualizeFromId( @PathParam(value = "id") String id ) throws Exception { PipeLine pipeline = new PipeLine(); InputStream input = null; Map<String, Object> params = new HashMap<>(); try { JSONObject questionnaire = questionnairesService.getQuestionnaireByID(id); JSONObject dataCollection = (JSONObject) ((JSONArray) questionnaire.get("DataCollection")).get(0); String name = dataCollection.get("Name").toString(); params.put("name", name); input = new ByteArrayInputStream(questionnaire.toJSONString().getBytes(StandardCharsets.UTF_8)); String uri = pipeline .from(input) .map(jsonToXML::transform, params) .map(xmlToDDI::transform, params) .map(ddiToXForm::transform, params) .map(xformToUri::transform, params) .transform(); return Response.seeOther(URI.create(uri)).build(); } catch(PoguesException e) { e.printStackTrace(); throw e; } catch (Exception e) { e.printStackTrace(); throw new PoguesException(500, e.getClass().getSimpleName(), e.getMessage()); } finally { input.close(); } } @POST @Path("json2xml") @Produces(MediaType.APPLICATION_XML) @Consumes(MediaType.APPLICATION_JSON) @ApiOperation( value = "Get Pogues XML From Pogues JSON", notes = "Returns a serialized XML based on a JSON entity that must comply with Pogues data model" ) @ApiResponses(value = { @ApiResponse(code = 200, message = "OK"), @ApiResponse(code = 500, message = "Error") }) @ApiImplicitParams(value = { @ApiImplicitParam(name = "json body", value = "JSON representation of the Pogues Model", paramType = "body", dataType = "string") }) public Response json2XML(@Context final HttpServletRequest request) throws Exception { try { return transform(request, jsonToXML); } catch(PoguesException e) { throw e; } catch (Exception e) { throw e; } } @POST @Path("xml2ddi") @Produces(MediaType.APPLICATION_XML) @Consumes(MediaType.APPLICATION_XML) @ApiOperation( value = "Get DDI From Pogues XML", notes = "Returns a DDI standard compliant document based on a XML representation of a Pogues data model entity" ) @ApiResponses(value = { @ApiResponse(code = 200, message = "OK"), @ApiResponse(code = 500, message = "Error") }) @ApiImplicitParams(value = { @ApiImplicitParam(name = "xml body", value = "XML representation of the Pogues Model", paramType = "body", dataType = "string") }) public Response xml2DDi(@Context final HttpServletRequest request) throws Exception { try { return transform(request, xmlToDDI); } catch(PoguesException e) { throw e; } catch (Exception e) { throw e; } } @POST @Path("ddi2xform") @Produces(MediaType.APPLICATION_XML) @Consumes(MediaType.APPLICATION_XML) @ApiOperation( value = "Get Pogues XForm From Pogues DDI metadata", notes = "Returns XForm description based on a DDI standard compliant document describing a Pogues Model entity" ) @ApiResponses(value = { @ApiResponse(code = 200, message = "OK"), @ApiResponse(code = 500, message = "Error") }) @ApiImplicitParams(value = { @ApiImplicitParam(name = "ddi body", value = "DDI representation of the Pogues Model", paramType = "body", dataType = "string") }) public Response ddi2XForm(@Context final HttpServletRequest request) throws Exception { try { return transform(request, ddiToXForm); } catch(PoguesException e) { throw e; } catch (Exception e) { throw e; } } @POST @Path("xform2uri/{name}") @Produces(MediaType.TEXT_PLAIN) @Consumes(MediaType.APPLICATION_XML) @ApiOperation( value = "Get Pogues visualization URI From Pogues XForm document", notes = "Returns the vizualisation URI of a form that was generated from XForm description found in body" ) @ApiResponses(value = { @ApiResponse(code = 200, message = "OK"), @ApiResponse(code = 500, message = "Error") }) @ApiImplicitParams(value = { @ApiImplicitParam(name = "xform body", value = "XForm document generated from Pogues DDI metadata", paramType = "body", dataType = "string") }) public String xForm2URI( @Context final HttpServletRequest request, @PathParam(value = "name") String name ) throws Exception { try { Map<String, Object> params = new HashMap<>(); params.put("name", name); String input = IOUtils.toString(request.getInputStream(), StandardCharsets.UTF_8); return xformToUri.transform(input, params); } catch(PoguesException e) { throw e; } catch (Exception e) { throw e; } } private Response transform(HttpServletRequest request, Transformer transformer) throws Exception { try { StreamingOutput stream = output -> { try { transformer.transform(request.getInputStream(), output, null); } catch (Exception e) { logger.error(e.getMessage()); throw new PoguesException(500, e.getMessage(), null); } }; return Response.ok(stream).build(); } catch (Exception e) { throw e; } } }
package gov.nih.nci.cananolab.ui.publication; /** * This class submits publication and assigns visibility * * @author tanq */ import gov.nih.nci.cananolab.domain.common.Author; import gov.nih.nci.cananolab.domain.common.Publication; import gov.nih.nci.cananolab.dto.common.PublicationBean; import gov.nih.nci.cananolab.dto.common.PublicationSummaryViewBean; import gov.nih.nci.cananolab.dto.common.UserBean; import gov.nih.nci.cananolab.dto.particle.SampleBean; import gov.nih.nci.cananolab.exception.SecurityException; import gov.nih.nci.cananolab.service.publication.PubMedXMLHandler; import gov.nih.nci.cananolab.service.publication.PublicationService; import gov.nih.nci.cananolab.service.publication.helper.PublicationServiceHelper; import gov.nih.nci.cananolab.service.publication.impl.PublicationServiceLocalImpl; import gov.nih.nci.cananolab.service.sample.SampleService; import gov.nih.nci.cananolab.service.sample.impl.SampleServiceLocalImpl; import gov.nih.nci.cananolab.service.security.AuthorizationService; import gov.nih.nci.cananolab.ui.core.BaseAnnotationAction; import gov.nih.nci.cananolab.ui.core.InitSetup; import gov.nih.nci.cananolab.ui.sample.InitCharacterizationSetup; import gov.nih.nci.cananolab.ui.sample.InitSampleSetup; import gov.nih.nci.cananolab.ui.security.InitSecuritySetup; import gov.nih.nci.cananolab.util.Constants; import gov.nih.nci.cananolab.util.DateUtils; import gov.nih.nci.cananolab.util.ExportUtils; import gov.nih.nci.cananolab.util.StringUtils; import java.util.ArrayList; import java.util.Arrays; import java.util.Calendar; import java.util.List; import java.util.SortedMap; import java.util.SortedSet; 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 org.apache.struts.action.ActionMessage; import org.apache.struts.action.ActionMessages; import org.apache.struts.validator.DynaValidatorForm; public class PublicationAction extends BaseAnnotationAction { public ActionForward create(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { ActionForward forward = null; PublicationForm theForm = (PublicationForm) form; PublicationBean publicationBean = (PublicationBean) theForm.get("file"); UserBean user = (UserBean) request.getSession().getAttribute("user"); publicationBean.setupDomain(Constants.FOLDER_PUBLICATION, user .getLoginName(), 0); PublicationService service = new PublicationServiceLocalImpl(); service.savePublication(publicationBean, user); // set visibility AuthorizationService authService = new AuthorizationService( Constants.CSM_APP_NAME); authService.assignVisibility(publicationBean.getDomainFile().getId() .toString(), publicationBean.getVisibilityGroups(), null); InitPublicationSetup.getInstance().persistPublicationDropdowns(request, publicationBean); ActionMessages msgs = new ActionMessages(); ActionMessage msg = new ActionMessage("message.submitPublication.file", publicationBean.getDomainFile().getTitle()); msgs.add(ActionMessages.GLOBAL_MESSAGE, msg); saveMessages(request, msgs); forward = mapping.findForward("success"); HttpSession session = request.getSession(); String sampleId = (String) session.getAttribute("docSampleId"); // String sampleId = request.getParameter("sampleId"); // if (sampleId != null) { // session.setAttribute("docSampleId", sampleId); // }else { // //if it is not calling from particle, remove previous set attribute // if applicable // session.removeAttribute("docSampleId"); // if (sampleId==null ||sampleId.length()==0) { // Object sampleIdObj = session.getAttribute("sampleId"); // if (sampleIdObj!=null) { // sampleId = sampleIdObj.toString(); // request.setAttribute("sampleId", sampleId); // }else { // request.removeAttribute("sampleId"); if (sampleId != null && sampleId.length() > 0) { SampleService sampleService = new SampleServiceLocalImpl(); SampleBean sampleBean = sampleService .findSampleById(sampleId, user); sampleBean.setLocation(Constants.LOCAL_SITE); forward = mapping.findForward("sampleSuccess"); } // session.removeAttribute("sampleId"); // to preselect the same characterization type after returning to the // summary page SortedSet<String> publicationCategories = InitSetup.getInstance() .getDefaultAndOtherLookupTypes(request, "publicationCategories", "Publication", "category", "otherCategory", true); List<String> allPublicationTypes = new ArrayList<String>( publicationCategories); int ind = allPublicationTypes.indexOf(((Publication) publicationBean .getDomainFile()).getCategory()) + 1; request.getSession().setAttribute( "onloadJavascript", "showSummary('" + ind + "', " + allPublicationTypes.size() + ")"); return forward; } public ActionForward setupNew(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { HttpSession session = request.getSession(); session.removeAttribute("publicationForm"); String sampleId = request.getParameter("sampleId"); InitPublicationSetup.getInstance().setPublicationDropdowns(request); UserBean user = (UserBean) request.getSession().getAttribute("user"); InitSampleSetup.getInstance().getAllSampleNames(request); if (sampleId != null && sampleId.trim().length() > 0 && session.getAttribute("otherSampleNames") == null) { InitSampleSetup.getInstance() .getOtherSampleNames(request, sampleId); } ActionForward forward = mapping.getInputForward(); if (sampleId != null && !sampleId.equals("null") && sampleId.trim().length() > 0) { forward = mapping.findForward("sampleSubmitPublication"); session.setAttribute("docSampleId", sampleId); } else { session.removeAttribute("docSampleId"); } return forward; } public ActionForward setupReport(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { HttpSession session = request.getSession(); String sampleId = request.getParameter("sampleId"); ActionForward forward = null; if (sampleId != null && !sampleId.equals("null") && sampleId.trim().length() > 0) { // forward = mapping.findForward("sampleSubmitReport"); forward = mapping.findForward("sampleSubmitPublication"); session.setAttribute("docSampleId", sampleId); } else { session.removeAttribute("docSampleId"); forward = mapping.findForward("publicationSubmitPublication"); // forward = mapping.findForward("publicationSubmitReport"); } DynaValidatorForm theForm = (DynaValidatorForm) form; // PublicationBean publicationBean = ((PublicationBean) // theForm.get("file")); PublicationBean publicationBean = new PublicationBean(); Publication pub = (Publication) publicationBean.getDomainFile(); pub.setStatus("published"); pub.setCategory("report"); publicationBean.setDomainFile(pub); theForm.set("file", publicationBean); return forward; } public ActionForward setupPubmed(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { PublicationForm theForm = (PublicationForm) form; PublicationBean pbean = (PublicationBean) theForm.get("file"); pbean.setFoundPubMedArticle(false); PubMedXMLHandler phandler = PubMedXMLHandler.getInstance(); String pubmedID = request.getParameter("pubmedId"); String sampleId = request.getParameter("sampleId"); HttpSession session = request.getSession(); ActionForward forward = null; if (sampleId != null && sampleId.trim().length() > 0) { forward = mapping.findForward("sampleSubmitPublication"); session.setAttribute("docSampleId", sampleId); } else { forward = mapping.findForward("publicationSubmitPublication"); session.removeAttribute("docSampleId"); } // clear publication data fields Publication publication = (Publication) pbean.getDomainFile(); publication.setTitle(""); publication.setDigitalObjectId(""); publication.setJournalName(""); publication.setStartPage(null); publication.setEndPage(null); publication.setYear(null); publication.setVolume(""); List<Author> authors = new ArrayList<Author>(); authors.add(new Author()); pbean.setAuthors(authors); if (pubmedID != null && pubmedID.length() > 0 && !pubmedID.equals("0")) { Long pubMedIDLong = 0L; try { pubMedIDLong = Long.valueOf(pubmedID); } catch (Exception ex) { ActionMessages msgs = new ActionMessages(); ActionMessage msg = new ActionMessage( "message.submitPublication.invalidPubmedId"); msgs.add(ActionMessages.GLOBAL_MESSAGE, msg); saveErrors(request, msgs); return forward; } phandler.parsePubMedXML(pubMedIDLong, pbean); if (!pbean.isFoundPubMedArticle()) { ActionMessages msgs = new ActionMessages(); ActionMessage msg = new ActionMessage( "message.submitPublication.pubmedArticleNotFound", pubmedID); msgs.add(ActionMessages.GLOBAL_MESSAGE, msg); saveMessages(request, msgs); return forward; } theForm.set("file", pbean); if (sampleId != null && sampleId.length() > 0) { forward = mapping.findForward("sampleSubmitPubmedPublication"); } else { forward = mapping.findForward("publicationSubmitPublication"); } } else { publication.setPubMedId(null); theForm.set("file", pbean); } return forward; } public ActionForward setupUpdate(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { HttpSession session = request.getSession(); String sampleId = request.getParameter("sampleId"); PublicationForm theForm = (PublicationForm) form; UserBean user = (UserBean) request.getSession().getAttribute("user"); if (sampleId != null && sampleId.trim().length() > 0) { session.setAttribute("docSampleId", sampleId); // set up other particles with the same primary point of contact InitSampleSetup.getInstance() .getOtherSampleNames(request, sampleId); } else { session.removeAttribute("docSampleId"); } String publicationId = request.getParameter("publicationId"); PublicationService publicationService = new PublicationServiceLocalImpl(); PublicationBean publicationBean = publicationService .findPublicationById(publicationId, user); theForm.set("file", publicationBean); InitPublicationSetup.getInstance().setPublicationDropdowns(request); // if sampleId is available direct to particle specific page Publication pub = (Publication) publicationBean.getDomainFile(); Long pubMedId = pub.getPubMedId(); ActionForward forward = getReturnForward(mapping, sampleId, pubMedId); return forward; } private ActionForward getReturnForward(ActionMapping mapping, String sampleId, Long pubMedId) { ActionForward forward = null; if (sampleId != null && sampleId.trim().length() > 0) { if (pubMedId != null && pubMedId > 0) { forward = mapping.findForward("sampleSubmitPubmedPublication"); } else { forward = mapping.findForward("sampleSubmitPublication"); } // request.setAttribute("sampleId", sampleId); } else { if (pubMedId != null && pubMedId > 0) { forward = mapping .findForward("publicationSubmitPubmedPublication"); } else { forward = mapping.findForward("publicationSubmitPublication"); } // request.removeAttribute("sampleId"); } return forward; } public ActionForward setupView(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { PublicationForm theForm = (PublicationForm) form; HttpSession session = request.getSession(); UserBean user = (UserBean) session.getAttribute("user"); String publicationId = request.getParameter("fileId"); String location = request.getParameter("location"); PublicationService publicationService = null; if (location.equals(Constants.LOCAL_SITE)) { publicationService = new PublicationServiceLocalImpl(); } // else { // String serviceUrl = InitSetup.getInstance().getGridServiceUrl( // request, location); // publicationService = new PublicationServiceRemoteImpl(serviceUrl); PublicationBean publicationBean = publicationService .findPublicationById(publicationId, user); theForm.set("file", publicationBean); InitPublicationSetup.getInstance().setPublicationDropdowns(request); // if sampleId is available direct to particle specific page String sampleId = request.getParameter("sampleId"); ActionForward forward = mapping.findForward("view"); if (sampleId != null) { forward = mapping.findForward("sampleViewPublication"); } return forward; } /** * Handle summary report print request. * * @param mapping * @param form * @param request * @param response * @return ActionForward * @throws Exception */ public ActionForward summaryPrint(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { // Prepare data. this.prepareSummary(mapping, form, request, response); // Marker that indicates page is for printing (hide tabs, links, etc). request.setAttribute("printView", Boolean.TRUE); PublicationSummaryViewBean summaryBean = (PublicationSummaryViewBean) request .getAttribute("publicationSummaryView"); // Filter out categories that not selected. String type = request.getParameter("type"); if (!StringUtils.isEmpty(type)) { SortedMap<String, List<PublicationBean>> categories = summaryBean .getCategory2Publications(); List<PublicationBean> pubs = categories.get(type); if (pubs != null) { categories.clear(); categories.put(type, pubs); summaryBean.setPublicationCategories(categories.keySet()); } } return mapping.findForward("summaryPrint"); } /** * Handle summary report view request. * * @param mapping * @param form * @param request * @param response * @return ActionForward * @throws Exception */ public ActionForward summaryView(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { // Prepare data. this.prepareSummary(mapping, form, request, response); // "actionName" is for constructing the Print/Export URL. request.setAttribute("actionName", request.getRequestURL().toString()); // TODO fill in detail // String location = request.getParameter("location"); // UserBean user = (UserBean) request.getSession().getAttribute("user"); // PublicationService publicationService = null; // if (location.equals(Constants.LOCAL_SITE)) { // publicationService = new PublicationServiceLocalImpl(); // } else { // String serviceUrl = InitSetup.getInstance().getGridServiceUrl( // request, location); // publicationService = new PublicationServiceRemoteImpl(serviceUrl); // String publicationId = request.getParameter("publicationId"); // PublicationBean pubBean = // publicationService.findPublicationById(publicationId); // checkVisibility(request, location, user, pubBean); // PublicationForm theForm = (PublicationForm) form; // theForm.set("file", pubBean); // String sampleId = request.getParameter("sampleId"); // ActionForward forward = null; // if(sampleId == null || sampleId.length() == 0) { // forward = mapping.findForward("publicationDetailView"); // } else { // forward = mapping.findForward("sampleDetailView"); // String submitType = request.getParameter("submitType"); // String requestUrl = request.getRequestURL().toString(); // String printLinkURL = requestUrl // + "?page=0&dispatch=printDetailView&sampleId=" + sampleId // + "&publicationId=" + publicationId + // "&submitType=" + submitType + "&location=" // + location; // request.getSession().setAttribute("printDetailViewLinkURL", // printLinkURL); return mapping.findForward("summaryView"); } /** * Handle summary report edit request. * * @param mapping * @param form * @param request * @param response * @return ActionForward * @throws Exception */ public ActionForward summaryEdit(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { //if session is expired or the url is clicked on directly UserBean user = (UserBean) request.getSession().getAttribute("user"); if (user==null) { return summaryView(mapping, form, request, response); } this.prepareSummary(mapping, form, request, response); // "actionName" is for constructing the Print/Export URL. request.setAttribute("actionName", request.getRequestURL().toString()); // TODO fill in detail // String location = request.getParameter("location"); // UserBean user = (UserBean) request.getSession().getAttribute("user"); // PublicationService publicationService = null; // if (location.equals(Constants.LOCAL_SITE)) { // publicationService = new PublicationServiceLocalImpl(); // } else { // String serviceUrl = InitSetup.getInstance().getGridServiceUrl( // request, location); // publicationService = new PublicationServiceRemoteImpl(serviceUrl); // String publicationId = request.getParameter("publicationId"); // PublicationBean pubBean = // publicationService.findPublicationById(publicationId); // checkVisibility(request, location, user, pubBean); // PublicationForm theForm = (PublicationForm) form; // theForm.set("file", pubBean); // String sampleId = request.getParameter("sampleId"); // ActionForward forward = null; // if(sampleId == null || sampleId.length() == 0) { // forward = mapping.findForward("publicationDetailView"); // } else { // forward = mapping.findForward("sampleDetailView"); // String submitType = request.getParameter("submitType"); // String requestUrl = request.getRequestURL().toString(); // String printLinkURL = requestUrl // + "?page=0&dispatch=printDetailView&sampleId=" + sampleId // + "&publicationId=" + publicationId + // "&submitType=" + submitType + "&location=" // + location; // request.getSession().setAttribute("printDetailViewLinkURL", // printLinkURL); return mapping.findForward("summaryEdit"); } /** * Handle summary report export request. * * @param mapping * @param form * @param request * @param response * @return ActionForward * @throws Exception */ public ActionForward summaryExport(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { // Prepare data. prepareSummary(mapping, form, request, response); PublicationSummaryViewBean summaryBean = (PublicationSummaryViewBean) request .getAttribute("publicationSummaryView"); // Filter out categories that not selected. String type = request.getParameter("type"); if (!StringUtils.isEmpty(type)) { SortedMap<String, List<PublicationBean>> categories = summaryBean .getCategory2Publications(); List<PublicationBean> pubs = categories.get(type); if (pubs != null) { categories.clear(); categories.put(type, pubs); summaryBean.setPublicationCategories(categories.keySet()); } } // Get sample name for constructing file name. PublicationForm theForm = (PublicationForm) form; String location = request.getParameter("location"); SampleBean sampleBean = setupSample(theForm, request, location, false); SampleService sampleService = null; PublicationService service = null; String sampleId = request.getParameter("sampleId"); if (Constants.LOCAL_SITE.equals(location)) { sampleService = new SampleServiceLocalImpl(); service = new PublicationServiceLocalImpl(); } // else { // // TODO: Implement remote service. // String serviceUrl = InitSetup.getInstance().getGridServiceUrl( // request, location); // service = new PublicationServiceRemoteImpl(serviceUrl); String fileName = this.getExportFileName(sampleBean.getDomain() .getName(), "summaryView"); ExportUtils.prepareReponseForExcell(response, fileName); PublicationServiceHelper.exportSummary(summaryBean, response .getOutputStream()); return null; } /** * Shared function for summaryView(), summaryEdit(), summaryExport() and * summaryPrint(). * * @param mapping * @param form * @param request * @param response * @return ActionForward * @throws Exception */ private void prepareSummary(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { PublicationForm theForm = (PublicationForm) form; String sampleId = theForm.getString("sampleId"); String location = theForm.getString("location"); setupSample(theForm, request, location, false); InitSetup.getInstance().getDefaultAndOtherLookupTypes(request, "publicationCategories", "Publication", "category", "otherCategory", true); UserBean user = (UserBean) request.getSession().getAttribute("user"); PublicationService publicationService = new PublicationServiceLocalImpl(); List<PublicationBean> publications = publicationService .findPublicationsBySampleId(sampleId, user); PublicationSummaryViewBean summaryView = new PublicationSummaryViewBean( publications); request.setAttribute("publicationSummaryView", summaryView); if (request.getParameter("clearTab") != null && request.getParameter("clearTab").equals("true")) { request.getSession().removeAttribute("onloadJavascript"); } } public ActionForward printDetailView(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { String location = request.getParameter("location"); UserBean user = (UserBean) request.getSession().getAttribute("user"); PublicationService publicationService = null; if (location.equals(Constants.LOCAL_SITE)) { publicationService = new PublicationServiceLocalImpl(); } // else { // String serviceUrl = InitSetup.getInstance().getGridServiceUrl( // request, location); // publicationService = new PublicationServiceRemoteImpl(serviceUrl); String publicationId = request.getParameter("publicationId"); PublicationBean pubBean = publicationService.findPublicationById( publicationId, user); PublicationForm theForm = (PublicationForm) form; theForm.set("file", pubBean); return mapping.findForward("publicationDetailPrintView"); } public ActionForward input(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { HttpSession session = request.getSession(); String sampleId = (String) session.getAttribute("docSampleId"); // save new entered other types InitPublicationSetup.getInstance().setPublicationDropdowns(request); PublicationForm theForm = (PublicationForm) form; PublicationBean publicationBean = ((PublicationBean) theForm .get("file")); String selectedPublicationType = ((Publication) publicationBean .getDomainFile()).getCategory(); if (selectedPublicationType != null) { SortedSet<String> types = (SortedSet<String>) request.getSession() .getAttribute("publicationCategories"); if (types != null) { types.add(selectedPublicationType); request.getSession().setAttribute("publicationCategories", types); } } String selectedPublicationStatus = ((Publication) publicationBean .getDomainFile()).getStatus(); if (selectedPublicationStatus != null) { SortedSet<String> statuses = (SortedSet<String>) request .getSession().getAttribute("publicationStatuses"); if (statuses != null) { statuses.add(selectedPublicationStatus); request.getSession().setAttribute("publicationStatuses", statuses); } } Publication pub = (Publication) publicationBean.getDomainFile(); theForm.set("file", publicationBean); // if pubMedId is available, the related fields should be set to read // only. Long pubMedId = pub.getPubMedId(); ActionForward forward = getReturnForward(mapping, sampleId, pubMedId); return forward; } public ActionForward detailView(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { String location = request.getParameter("location"); UserBean user = (UserBean) request.getSession().getAttribute("user"); PublicationService publicationService = null; if (location.equals(Constants.LOCAL_SITE)) { publicationService = new PublicationServiceLocalImpl(); } // else { // String serviceUrl = InitSetup.getInstance().getGridServiceUrl( // request, location); // publicationService = new PublicationServiceRemoteImpl(serviceUrl); String publicationId = request.getParameter("publicationId"); PublicationBean pubBean = publicationService.findPublicationById( publicationId, user); PublicationForm theForm = (PublicationForm) form; theForm.set("file", pubBean); String sampleId = request.getParameter("sampleId"); ActionForward forward = null; if (sampleId == null || sampleId.length() == 0) { forward = mapping.findForward("publicationDetailView"); } else { forward = mapping.findForward("sampleDetailView"); } String requestUrl = request.getRequestURL().toString(); String printLinkURL = requestUrl + "?page=0&dispatch=printDetailView&sampleId=" + sampleId + "&publicationId=" + publicationId + "&location=" + location; request.getSession().setAttribute("printDetailViewLinkURL", printLinkURL); return forward; } public ActionForward addAuthor(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { PublicationForm theForm = (PublicationForm) form; PublicationBean pbean = (PublicationBean) theForm.get("file"); pbean.addAuthor(); return mapping.getInputForward(); } public boolean loginRequired() { return true; } public boolean canUserExecute(UserBean user) throws SecurityException { return InitSecuritySetup.getInstance().userHasCreatePrivilege(user, Constants.CSM_PG_PUBLICATION); } protected boolean validateResearchAreas(HttpServletRequest request, String[] researchAreas) throws Exception { ActionMessages msgs = new ActionMessages(); boolean noErrors = true; if (researchAreas == null || researchAreas.length == 0) { ActionMessage msg = new ActionMessage( "submitPublicationForm.file.researchArea", "researchAreas"); msgs.add(ActionMessages.GLOBAL_MESSAGE, msg); this.saveErrors(request, msgs); noErrors = false; } else { System.out.println("validateResearchAreas ==" + Arrays.toString(researchAreas)); } return noErrors; } public ActionForward exportDetail(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { String location = request.getParameter("location"); UserBean user = (UserBean) request.getSession().getAttribute("user"); PublicationService publicationService = null; if (location.equals(Constants.LOCAL_SITE)) { publicationService = new PublicationServiceLocalImpl(); } // else { // String serviceUrl = InitSetup.getInstance().getGridServiceUrl( // request, location); // publicationService = new PublicationServiceRemoteImpl(serviceUrl); String publicationId = request.getParameter("publicationId"); PublicationBean pubBean = publicationService.findPublicationById( publicationId, user); PublicationForm theForm = (PublicationForm) form; theForm.set("file", pubBean); String title = pubBean.getDomainFile().getTitle(); if (title != null && title.length() > 10) { title = title.substring(0, 10); } String fileName = this.getExportFileName(title, "detailView"); ExportUtils.prepareReponseForExcell(response, fileName); PublicationServiceHelper.exportDetail(pubBean, response .getOutputStream()); return null; } private String getExportFileName(String titleName, String viewType) { List<String> nameParts = new ArrayList<String>(); nameParts.add(titleName); nameParts.add("Publication"); nameParts.add(viewType); nameParts.add(DateUtils.convertDateToString(Calendar.getInstance() .getTime())); String exportFileName = StringUtils.join(nameParts, "_"); return exportFileName; } }
package gr.iti.mklab.sfc.filters; import java.util.Map; import gr.iti.mklab.classifiers.ClassificationResult; import gr.iti.mklab.classifiers.EnvironmentalClassification; import gr.iti.mklab.framework.common.domain.Item; import gr.iti.mklab.framework.common.domain.config.Configuration; import gr.iti.mklab.sfc.filters.ItemFilter; public class EnvironmentalClassifier extends ItemFilter { private EnvironmentalClassification ec; private double threshold; public EnvironmentalClassifier(Configuration configuration) { super(configuration); threshold = Double.parseDouble(configuration.getParameter("threshold", "0.3")); ec = new EnvironmentalClassification(); } @Override public boolean accept(Item item) { if(!"Twitter".equals(item.getSource())) { return true; } String lang = item.getLanguage(); String text = ""; String title = item.getTitle(); String description = item.getDescription(); if(title != null) { text += " " + title; } if (description != null) { text += " " + title; } try { ClassificationResult result = ec.classify(text, lang, false); Map<String, Double> probMap = result.getFirstClassifierProbabilityMap(); if(probMap.get("Relevant") > 0.5) { item.addTopic("environment", probMap.get("Relevant")); if(result.getSecondClassifierProbabilitityMap() != null) { Map<String, Double> subTopics = result.getSecondClassifierProbabilitityMap(); for(String subTopic : subTopics.keySet()) { if(subTopics.get(subTopic) > threshold) { item.addTopic("environment." + subTopic, subTopics.get(subTopic)); } } } return true; } else { if(probMap.get("Relevant") > threshold) { return true; } return false; } } catch (Exception e) { return false; } } @Override public String name() { return "EnvironmentalClassifier"; } }
package io.collap.bryg.compiler.resolver; import java.io.File; import java.util.ArrayList; import java.util.Enumeration; import java.util.List; import java.util.Stack; import java.util.jar.JarEntry; import java.util.jar.JarFile; // TODO: Add the options to skip files and folders. Or do the opposite, so the user must allow specific files and folders. // This improvement will reduce the cost of finding the classes by a huge margin (Currently, big libraries might take // the class name finder up to a second to complete). public class ClassNameFinder { private List<String> paths = new ArrayList<> (); private ClassNameVisitor visitor; public ClassNameFinder (ClassNameVisitor visitor) { this.visitor = visitor; /* The *-wildcard signals that all jars in the directory ought to be included in the classpath. */ addPath (System.getProperty ("java.home") + File.separator + "lib" + File.separator + "*"); /* Add all directories and jars from the classpath. */ String[] paths = System.getProperty ("java.class.path").split (System.getProperty ("path.separator")); for (String path : paths) { addPath (path); } } public void addPath (String path) { paths.add (path); } public void crawl () { crawlPaths (paths); } public void crawlPaths (List<String> paths) { for (String path : paths) { crawlPath (path); } } public void crawlPath (String path) { if (path.endsWith ("*")) { /* Wildcard path. */ path = path.substring (0, path.length () - 1); File directory = new File (path); if (!directory.isDirectory ()) { System.out.println (path + " is not a directory!"); return; } /* Crawl jar files. */ File[] children = directory.listFiles (); if (children != null) { for (File child : children) { if (child.getName ().endsWith (".jar")) { crawlJarFile (child); } } } }else { File file = new File (path); if (file.isDirectory ()) { crawlDirectory (file); }else if (file.getName ().endsWith (".jar")) { crawlJarFile (file); } } } public void crawlDirectory (File file) { crawlDirectory (file, file); } private void crawlDirectory (File root, File file) { if (file.isDirectory ()) { File[] files = file.listFiles (); if (files != null) { for (File child : files) { crawlDirectory (root, child); } } }else { if (file.getName ().endsWith (".class")) { visitor.visit (createClassName (root, file)); } } } private String createClassName (File root, File file) { Stack<String> names = new Stack<> (); String name = file.getName (); names.push (name.substring (0, name.lastIndexOf ('.'))); /* Push names. */ for (File directory = file.getParentFile (); directory != null && !directory.equals (root); directory = directory.getParentFile ()) { names.push (directory.getName ()); } /* Build the full class name. */ StringBuilder builder = new StringBuilder (32); while (!names.empty ()) { builder.append (names.pop ()); if (!names.empty ()) { builder.append ('.'); } } return builder.toString(); } public void crawlJarFile (File jarFile) { JarFile jar; try { jar = new JarFile (jarFile); } catch (Exception ex) { System.out.println ("Jar file " + jarFile.getAbsolutePath () + " not found!"); ex.printStackTrace (); return; } Enumeration<JarEntry> entries = jar.entries (); while (entries.hasMoreElements ()) { JarEntry entry = entries.nextElement (); String entryPath = entry.getName (); int extIndex = entryPath.lastIndexOf (".class"); if (extIndex > 0) { visitor.visit (entryPath.substring (0, extIndex).replace ("/", ".")); } } } }
package gov.nih.nci.ncicb.cadsr.loader.event; import gov.nih.nci.ncicb.cadsr.domain.*; import gov.nih.nci.ncicb.cadsr.loader.ElementsLists; import gov.nih.nci.ncicb.cadsr.loader.ReviewTracker; import org.apache.log4j.Logger; import java.util.*; import gov.nih.nci.ncicb.cadsr.loader.util.*; import gov.nih.nci.ncicb.cadsr.loader.defaults.*; import gov.nih.nci.ncicb.cadsr.loader.ext.*; import gov.nih.nci.ncicb.cadsr.loader.ChangeTracker; import gov.nih.nci.ncicb.cadsr.loader.ReviewTrackerType; import gov.nih.nci.ncicb.cadsr.loader.validator.ValidationWarning; import gov.nih.nci.ncicb.cadsr.loader.validator.ValidationError; import gov.nih.nci.ncicb.cadsr.loader.validator.ValidationItems; /** * This class implements UMLHandler specifically to handle UML events and * convert them into caDSR objects.<br> The handler's responsibility is to * transform events received into cadsr domain objects, and store those objects * in the Elements List. * * @author <a href="mailto:ludetc@mail.nih.gov">Christophe Ludet</a> */ public class UMLDefaultHandler implements UMLHandler, CadsrModuleListener, RunModeListener { private ElementsLists elements; private Logger logger = Logger.getLogger(UMLDefaultHandler.class.getName()); private List packageList = new ArrayList(); private ReviewTracker reviewTracker; private CadsrModule cadsrModule; // keeps track of the mapping between an oc and the DE that set it's public id // key = oc Id / version // Value = the DE that set oc id / version private Map<String, DataElement> ocMapping = new HashMap<String, DataElement>(); private InheritedAttributeList inheritedAttributes = InheritedAttributeList.getInstance(); public UMLDefaultHandler() { this.elements = ElementsLists.getInstance(); } public void setRunMode(RunMode runMode) { if(runMode.equals(RunMode.Curator)) { reviewTracker = reviewTracker.getInstance(ReviewTrackerType.Curator); } else { reviewTracker = reviewTracker.getInstance(ReviewTrackerType.Owner); } } public void newPackage(NewPackageEvent event) { logger.info("Package: " + event.getName()); // handle this here if the package has GME info. If not, let classes handle package so we don't add empty package. if(!StringUtil.isEmpty(event.getGmeNamespace())) { ClassificationSchemeItem csi = DomainObjectFactory.newClassificationSchemeItem(); String pName = event.getName(); csi.setName(pName); if (!packageList.contains(pName)) { elements.addElement(csi); packageList.add(pName); } AlternateName gmeNamespaceName = DomainObjectFactory.newAlternateName(); gmeNamespaceName.setType(AlternateName.TYPE_GME_NAMESPACE); gmeNamespaceName.setName(event.getGmeNamespace()); csi.addAlternateName(gmeNamespaceName); } } public void newOperation(NewOperationEvent event) { logger.debug("Operation: " + event.getClassName() + "." + event.getName()); } public void newValueDomain(NewValueDomainEvent event) { logger.info("Value Domain: " + event.getName()); List<Concept> concepts = createConcepts(event); ValueDomain vd = DomainObjectFactory.newValueDomain(); if(!StringUtil.isEmpty(event.getVdId()) && event.getVdVersion() != null) { ValueDomain existingVd = null; Map<String, Object> queryFields = new HashMap<String, Object>(); queryFields.put(CadsrModule.PUBLIC_ID, event.getVdId()); queryFields.put(CadsrModule.VERSION, event.getVdVersion()); List<ValueDomain> result = null; try { result = new ArrayList<ValueDomain>(cadsrModule.findValueDomain(queryFields)); } catch (Exception e){ logger.error("Could not query cadsr module ", e); } // end of try-catch if(result.size() == 0) { // ChangeTracker changeTracker = ChangeTracker.getInstance(); ValidationError item = new ValidationError (PropertyAccessor.getProperty("local.vd.doesnt.exist", event.getName(), event.getVdId() + "v" + event.getVdVersion()), vd); ValidationItems.getInstance() .addItem(item); vd.setPublicId(null); vd.setVersion(null); // changeTracker.put // (className + "." + attributeName, // true); } else { existingVd = result.get(0); vd.setLongName(existingVd.getLongName()); vd.setPreferredDefinition(existingVd.getPreferredDefinition()); vd.setVdType(existingVd.getVdType()); vd.setDataType(existingVd.getDataType()); vd.setConceptualDomain(existingVd.getConceptualDomain()); vd.setRepresentation(existingVd.getRepresentation()); vd.setConceptDerivationRule(existingVd.getConceptDerivationRule()); } } else { vd.setLongName(event.getName()); vd.setPreferredDefinition(event.getDescription()); vd.setVdType(event.getType()); vd.setDataType(event.getDatatype()); ConceptualDomain cd = DomainObjectFactory.newConceptualDomain(); cd.setPublicId(event.getCdId()); cd.setVersion(event.getCdVersion()); // un comment the following to lookup CD. // Map<String, Object> queryFields = // new HashMap<String, Object>(); // queryFields.put(CadsrModule.PUBLIC_ID, event.getPersistenceId()); // queryFields.put(CadsrModule.VERSION, event.getPersistenceVersion()); // List<ConceptualDomain> result = null; // try { // result = new ArrayList<ConceptualDomain>(cadsrModule.findConceptualDomain(queryFields)); // } catch (Exception e){ // logger.error("Could not query cadsr module ", e); // } // end of try-catch // if(result.size() > 0) { // cd = result.get(0); vd.setConceptualDomain(cd); Representation repTerm = DomainObjectFactory.newRepresentation(); repTerm.setPublicId(event.getRepTermId()); repTerm.setVersion(event.getRepTermVersion()); vd.setRepresentation(repTerm); // if(concepts.size() > 0) vd.setConceptDerivationRule(ConceptUtil.createConceptDerivationRule(concepts, false)); } // create CSI for package (since 3.2) ClassificationSchemeItem csi = DomainObjectFactory.newClassificationSchemeItem(); String pName = event.getPackageName(); csi.setName(pName); if (!packageList.contains(pName)) { elements.addElement(csi); packageList.add(pName); } AdminComponentClassSchemeClassSchemeItem acCsCsi = DomainObjectFactory.newAdminComponentClassSchemeClassSchemeItem(); ClassSchemeClassSchemeItem csCsi = DomainObjectFactory.newClassSchemeClassSchemeItem(); csCsi.setCsi(csi); acCsCsi.setCsCsi(csCsi); List<AdminComponentClassSchemeClassSchemeItem> l = new ArrayList<AdminComponentClassSchemeClassSchemeItem>(); l.add(acCsCsi); vd.setAcCsCsis(l); elements.addElement(vd); reviewTracker.put(event.getName(), event.isReviewed()); } public void newValueMeaning(NewValueMeaningEvent event) { logger.info("Value Meaning: " + event.getName()); List<Concept> concepts = createConcepts(event); ValueDomain vd = LookupUtil.lookupValueDomain(event.getValueDomainName()); ValueMeaning vm = DomainObjectFactory.newValueMeaning(); vm.setLongName(event.getName()); vm.setLifecycle(UMLDefaults.getInstance().getLifecycle()); Concept[] vmConcepts = new Concept[concepts.size()]; concepts.toArray(vmConcepts); // Definition vmAltDef = DomainObjectFactory.newDefinition(); // vmAltDef.setType(Definition.TYPE_UML_VM); // if(!StringUtil.isEmpty(event.getDescription())) { // vmAltDef.setDefinition(event.getDescription()); // } else { // // vmAltDef.setDefinition(ValueMeaning.DEFAULT_DEFINITION); // if this VM has concepts, then use evs definition // if VM has no concept, then use user defined definition if(concepts != null && concepts.size() > 0) { vm.setPreferredDefinition(ConceptUtil .preferredDefinitionFromConcepts(vmConcepts)); // if(!StringUtil.isEmpty(event.getDescription())) // vm.addDefinition(vmAltDef); } else { if(!StringUtil.isEmpty(event.getDescription())) { vm.setPreferredDefinition(event.getDescription()); } else vm.setPreferredDefinition(ValueMeaning.DEFAULT_DEFINITION); // if(!StringUtil.isEmpty(event.getDescription())) // vm.addDefinition(vmAltDef); } vm.setConceptDerivationRule(ConceptUtil.createConceptDerivationRule(concepts, true)); PermissibleValue pv = DomainObjectFactory.newPermissibleValue(); pv.setValueMeaning(vm); pv.setValue(event.getName()); pv.setLifecycle(UMLDefaults.getInstance().getLifecycle()); vd.addPermissibleValue(pv); AlternateName vmAltName = DomainObjectFactory.newAlternateName(); vmAltName.setType(AlternateName.TYPE_UML_VM); vmAltName.setName(event.getName()); vm.addAlternateName(vmAltName); if(!StringUtil.isEmpty(event.getDescription())) { Definition vmAltDef = DomainObjectFactory.newDefinition(); vmAltDef.setType(Definition.TYPE_UML_VM); vmAltDef.setDefinition(event.getDescription()); vm.addDefinition(vmAltDef); } elements.addElement(vm); reviewTracker.put("ValueDomains." + event.getValueDomainName() + "." + event.getName(), event.isReviewed()); } public void newClass(NewClassEvent event) { logger.info("Class: " + event.getName()); List<Concept> concepts = createConcepts(event); ObjectClass oc = DomainObjectFactory.newObjectClass(); // store concept codes in preferredName oc.setPreferredName(ConceptUtil.preferredNameFromConcepts(concepts)); oc.setLongName(event.getName()); if(event.getDescription() != null && event.getDescription().length() > 0) oc.setPreferredDefinition(event.getDescription()); else oc.setPreferredDefinition(""); elements.addElement(oc); reviewTracker.put(event.getName(), event.isReviewed()); ClassificationSchemeItem csi = DomainObjectFactory.newClassificationSchemeItem(); String pName = event.getPackageName(); csi.setName(pName); if (!packageList.contains(pName)) { elements.addElement(csi); packageList.add(pName); } // Store package names AdminComponentClassSchemeClassSchemeItem acCsCsi = DomainObjectFactory.newAdminComponentClassSchemeClassSchemeItem(); ClassSchemeClassSchemeItem csCsi = DomainObjectFactory.newClassSchemeClassSchemeItem(); csCsi.setCsi(csi); acCsCsi.setCsCsi(csCsi); List<AdminComponentClassSchemeClassSchemeItem> l = new ArrayList<AdminComponentClassSchemeClassSchemeItem>(); l.add(acCsCsi); oc.setAcCsCsis(l); AlternateName fullName = DomainObjectFactory.newAlternateName(); fullName.setType(AlternateName.TYPE_CLASS_FULL_NAME); fullName.setName(event.getName()); AlternateName className = DomainObjectFactory.newAlternateName(); className.setType(AlternateName.TYPE_UML_CLASS); className.setName(event.getName().substring(event.getName().lastIndexOf(".") + 1)); if(!StringUtil.isEmpty(event.getGmeNamespace())) { AlternateName gmeNamespaceName = DomainObjectFactory.newAlternateName(); gmeNamespaceName.setType(AlternateName.TYPE_GME_NAMESPACE); gmeNamespaceName.setName(event.getGmeNamespace()); oc.addAlternateName(gmeNamespaceName); } if(!StringUtil.isEmpty(event.getGmeXmlElement())) { AlternateName gmeXmlElementName = DomainObjectFactory.newAlternateName(); gmeXmlElementName.setType(AlternateName.TYPE_GME_XML_ELEMENT); gmeXmlElementName.setName(event.getGmeXmlElement()); oc.addAlternateName(gmeXmlElementName); } oc.addAlternateName(fullName); oc.addAlternateName(className); } public void newAttribute(NewAttributeEvent event) { logger.info("Attribute: " + event.getClassName() + "." + event.getName()); DataElement de = DomainObjectFactory.newDataElement(); // populate if there is valid existing mapping DataElement existingDe = null; if(event.getPersistenceId() != null) { existingDe = findExistingDe(event.getPersistenceId(), event.getPersistenceVersion(), de, event.getClassName(), event.getName()); } List<Concept> concepts = createConcepts(event); Property prop = DomainObjectFactory.newProperty(); // store concept codes in preferredName prop.setPreferredName(ConceptUtil.preferredNameFromConcepts(concepts)); // prop.setPreferredName(event.getName()); prop.setLongName(event.getName()); String propName = event.getName(); String s = event.getClassName(); int ind = s.lastIndexOf("."); String className = s.substring(ind + 1); String packageName = s.substring(0, ind); DataElementConcept dec = DomainObjectFactory.newDataElementConcept(); dec.setLongName(className + ":" + propName); dec.setProperty(prop); logger.debug("DEC LONG_NAME: " + dec.getLongName()); ObjectClass oc = DomainObjectFactory.newObjectClass(); List<ObjectClass> ocs = elements.getElements(oc); for (ObjectClass o : ocs) { String fullClassName = null; for(AlternateName an : o.getAlternateNames()) { if(an.getType().equals(AlternateName.TYPE_CLASS_FULL_NAME)) fullClassName = an.getName(); } if (fullClassName.equals(event.getClassName())) { oc = o; } } dec.setObjectClass(oc); de.setDataElementConcept(dec); String datatype = event.getType().trim(); // save the datatype. We will use it if we clear a CDE mapping. elements.addElement(new AttributeDatatypePair(packageName + "." + className + "." + propName, datatype.toLowerCase())); if(DatatypeMapping.getKeys().contains(datatype.toLowerCase())) datatype = DatatypeMapping.getMapping().get(datatype.toLowerCase()); if(existingDe != null) { mapToExistingDE(oc, de, existingDe, event.getClassName(), event.getName()); } else { de.setLongName(dec.getLongName() + " " + event.getType()); } if(de.getValueDomain() == null) { ValueDomain vd = DomainObjectFactory.newValueDomain(); vd.setLongName(datatype); if(event.getTypeId() != null) { populateExistingVd(vd, event.getTypeId(), event.getTypeVersion(), event.getClassName() + "." + event.getName()); } de.setValueDomain(vd); } logger.debug("DE LONG_NAME: " + de.getLongName()); // Store alt Name for DE: // packageName.ClassName.PropertyName AlternateName fullName = DomainObjectFactory.newAlternateName(); fullName.setType(AlternateName.TYPE_FULL_NAME); fullName.setName(packageName + "." + className + "." + propName); de.addAlternateName(fullName); // Store alt Name for DE: // ClassName:PropertyName fullName = DomainObjectFactory.newAlternateName(); fullName.setType(AlternateName.TYPE_UML_DE); fullName.setName(className + ":" + propName); de.addAlternateName(fullName); if(!StringUtil.isEmpty(event.getGmeXmlLocRef())) { AlternateName gmeXmlLocRefName = DomainObjectFactory.newAlternateName(); gmeXmlLocRefName.setType(AlternateName.TYPE_GME_XML_LOC_REF); gmeXmlLocRefName.setName(event.getGmeXmlLocRef()); de.addAlternateName(gmeXmlLocRefName); } if(!StringUtil.isEmpty(event.getDescription())) { Definition altDef = DomainObjectFactory.newDefinition(); altDef.setType(Definition.TYPE_UML_DE); altDef.setDefinition(event.getDescription()); de.addDefinition(altDef); altDef = DomainObjectFactory.newDefinition(); altDef.setType(Definition.TYPE_UML_DEC); altDef.setDefinition(event.getDescription()); dec.addDefinition(altDef); } // Add packages to Prop, DE and DEC. prop.setAcCsCsis(oc.getAcCsCsis()); de.setAcCsCsis(oc.getAcCsCsis()); dec.setAcCsCsis(oc.getAcCsCsis()); reviewTracker.put(event.getClassName() + "." + event.getName(), event.isReviewed()); elements.addElement(de); elements.addElement(dec); elements.addElement(prop); } private DataElement findExistingDe(String id, Float version, DataElement de, String className, String attributeName) { DataElement existingDe = null; Map<String, Object> queryFields = new HashMap<String, Object>(); queryFields.put(CadsrModule.PUBLIC_ID, id); queryFields.put(CadsrModule.VERSION, version); List<DataElement> result = null; try { result = new ArrayList<DataElement>(cadsrModule.findDataElement(queryFields)); } catch (Exception e){ logger.error("Could not query cadsr module ", e); } // end of try-catch if(result.size() == 0) { ChangeTracker changeTracker = ChangeTracker.getInstance(); ValidationError item = new ValidationError(PropertyAccessor.getProperty("de.doesnt.exist", className + "." + attributeName, id + "v" + version), de); item.setIncludeInInherited(true); ValidationItems.getInstance() .addItem(item); de.setPublicId(null); de.setVersion(null); changeTracker.put (className + "." + attributeName, true); } else { existingDe = result.get(0); } return existingDe; } private void mapToExistingDE(ObjectClass oc, DataElement de, DataElement existingDe, String className, String attributeName) { if(existingDe.getDataElementConcept().getObjectClass() == null || existingDe.getDataElementConcept().getProperty() == null) { ValidationWarning item = new ValidationWarning(PropertyAccessor.getProperty("de.invalid"),de); ValidationItems.getInstance() .addItem(item); return; } if(oc.getPublicId() != null) { // Verify conflicts if(!existingDe.getDataElementConcept().getObjectClass().getPublicId().equals(oc.getPublicId()) || !existingDe.getDataElementConcept().getObjectClass().getVersion().equals(oc.getVersion())) { // Oc was already mapped by an existing DE. This DE conflicts with the previous mapping. ValidationError item = new ValidationError(PropertyAccessor.getProperty("de.conflict", new String[] {className + "." + attributeName, ocMapping.get(ConventionUtil.publicIdVersion(oc)).getLongName()}), de); item.setIncludeInInherited(true); ValidationItems.getInstance() .addItem(item); } } else { oc.setPublicId(existingDe.getDataElementConcept().getObjectClass().getPublicId()); oc.setVersion(existingDe.getDataElementConcept().getObjectClass().getVersion()); // Keep track so if there's conflict, we know both ends of the conflict ocMapping.put(ConventionUtil.publicIdVersion(oc), de); oc.setLongName(existingDe.getDataElementConcept().getObjectClass().getLongName()); oc.setPreferredName(""); ChangeTracker changeTracker = ChangeTracker.getInstance(); changeTracker.put (className, true); } // The DE's property was already set, probably by the parent. It must be the same. We don't override here. if(de.getDataElementConcept().getProperty().getPublicId() != null) { if(!existingDe.getDataElementConcept().getProperty().getPublicId().equals(de.getDataElementConcept().getProperty().getPublicId()) || !existingDe.getDataElementConcept().getProperty().getVersion().equals(de.getDataElementConcept().getProperty().getVersion()) ) { ValidationError item = new ValidationError(PropertyAccessor.getProperty("inherited.and.parent.property.mismatch", new String[] {className + "." + attributeName, ocMapping.get(ConventionUtil.publicIdVersion(oc)).getLongName()}), de); item.setIncludeInInherited(true); ValidationItems.getInstance() .addItem(item); } return; } de.getDataElementConcept().getProperty().setPublicId(existingDe.getDataElementConcept().getProperty().getPublicId()); de.getDataElementConcept().getProperty().setVersion(existingDe.getDataElementConcept().getProperty().getVersion()); de.setLongName(existingDe.getLongName()); de.setContext(existingDe.getContext()); de.setPublicId(existingDe.getPublicId()); de.setVersion(existingDe.getVersion()); de.setLatestVersionIndicator(existingDe.getLatestVersionIndicator()); de.setValueDomain(existingDe.getValueDomain()); } private void populateExistingVd(ValueDomain vd, String vdId, Float vdVersion, String attributeName) { Map<String, Object> queryFields = new HashMap<String, Object>(); queryFields.put(CadsrModule.PUBLIC_ID, vdId); queryFields.put(CadsrModule.VERSION, vdVersion); List<ValueDomain> result = null; try { result = new ArrayList<ValueDomain>(cadsrModule.findValueDomain(queryFields)); } catch (Exception e){ logger.error("Could not query cadsr module ", e); } // end of try-catch if(result.size() == 0) { ChangeTracker changeTracker = ChangeTracker.getInstance(); ValidationError item = new ValidationError(PropertyAccessor.getProperty("vd.doesnt.exist", attributeName, vdId + "v" + vdVersion), null); item.setIncludeInInherited(true); ValidationItems.getInstance() .addItem(item); vd.setPublicId(null); vd.setVersion(null); changeTracker.put (attributeName, true); } else { ValueDomain existingVd = result.get(0); vd.setLongName(existingVd.getLongName()); vd.setPublicId(existingVd.getPublicId()); vd.setVersion(existingVd.getVersion()); vd.setContext(existingVd.getContext()); vd.setDataType(existingVd.getDataType()); } } public void newInterface(NewInterfaceEvent event) { logger.debug("Interface: " + event.getName()); } public void newStereotype(NewStereotypeEvent event) { logger.debug("Stereotype: " + event.getName()); } public void newDataType(NewDataTypeEvent event) { logger.debug("DataType: " + event.getName()); } public void newAssociation(NewAssociationEvent event) { ObjectClassRelationship ocr = DomainObjectFactory.newObjectClassRelationship(); ObjectClass oc = DomainObjectFactory.newObjectClass(); NewAssociationEndEvent aEvent = event.getAEvent(); NewAssociationEndEvent bEvent = event.getBEvent(); NewAssociationEndEvent sEvent = null; NewAssociationEndEvent tEvent = null; List<ObjectClass> ocs = elements.getElements(oc); boolean aDone = false, bDone = false; for(ObjectClass o : ocs) { String classFullName = null; for(AlternateName an : o.getAlternateNames()) { if(an.getType().equals(AlternateName.TYPE_CLASS_FULL_NAME)) classFullName = an.getName(); } if (classFullName == null) { System.err.println("No full class name found for "+o.getLongName()); continue; } if (!aDone && (classFullName.equals(aEvent.getClassName()))) { if (event.getDirection().equals("B")) { sEvent = aEvent; ocr.setSource(o); ocr.setSourceRole(aEvent.getRoleName()); ocr.setSourceLowCardinality(aEvent.getLowCardinality()); ocr.setSourceHighCardinality(aEvent.getHighCardinality()); } else { tEvent = aEvent; ocr.setTarget(o); ocr.setTargetRole(aEvent.getRoleName()); ocr.setTargetLowCardinality(aEvent.getLowCardinality()); ocr.setTargetHighCardinality(aEvent.getHighCardinality()); } aDone = true; } if (!bDone && (classFullName.equals(bEvent.getClassName()))) { if (event.getDirection().equals("B")) { tEvent = bEvent; ocr.setTarget(o); ocr.setTargetRole(bEvent.getRoleName()); ocr.setTargetLowCardinality(bEvent.getLowCardinality()); ocr.setTargetHighCardinality(bEvent.getHighCardinality()); } else { sEvent = bEvent; ocr.setSource(o); ocr.setSourceRole(bEvent.getRoleName()); ocr.setSourceLowCardinality(bEvent.getLowCardinality()); ocr.setSourceHighCardinality(bEvent.getHighCardinality()); } bDone = true; } } if (event.getDirection().equals("AB")) { ocr.setDirection(ObjectClassRelationship.DIRECTION_BOTH); } else { ocr.setDirection(ObjectClassRelationship.DIRECTION_SINGLE); } ocr.setLongName(event.getRoleName()); ocr.setType(ObjectClassRelationship.TYPE_HAS); if(event.getConcepts() != null && event.getConcepts().size() > 0) ocr.setConceptDerivationRule( ConceptUtil.createConceptDerivationRule(createConcepts(event), true)); if(sEvent.getConcepts() != null && sEvent.getConcepts().size() > 0) ocr.setSourceRoleConceptDerivationRule( ConceptUtil.createConceptDerivationRule(createConcepts(sEvent), true)); if(tEvent.getConcepts() != null && tEvent.getConcepts().size() > 0) ocr.setTargetRoleConceptDerivationRule( ConceptUtil.createConceptDerivationRule(createConcepts(tEvent), true)); if(!aDone) logger.debug("!aDone: " + aEvent.getClassName() + " -- " + bEvent.getClassName()); if(!bDone) logger.debug("!bDone: " + aEvent.getClassName() + " -- " + bEvent.getClassName()); if(!StringUtil.isEmpty(event.getGmeSourceLocRef())) { AlternateName an = DomainObjectFactory.newAlternateName(); an.setType(AlternateName.TYPE_GME_SRC_XML_LOC_REF); an.setName(event.getGmeSourceLocRef()); ocr.addAlternateName(an); } if(!StringUtil.isEmpty(event.getGmeTargetLocRef())) { AlternateName an = DomainObjectFactory.newAlternateName(); an.setType(AlternateName.TYPE_GME_TARGET_XML_LOC_REF); an.setName(event.getGmeTargetLocRef()); ocr.addAlternateName(an); } elements.addElement(ocr); OCRRoleNameBuilder nameBuilder = new OCRRoleNameBuilder(); String fullName = nameBuilder.buildRoleName(ocr); reviewTracker.put(fullName, event.isReviewed()); reviewTracker.put(fullName+" Source", sEvent.isReviewed()); reviewTracker.put(fullName+" Target", tEvent.isReviewed()); } public void newGeneralization(NewGeneralizationEvent event) { ObjectClassRelationship ocr = DomainObjectFactory.newObjectClassRelationship(); AlternateName an = DomainObjectFactory.newAlternateName(); an.setName(event.getParentClassName()); an.setType(AlternateName.TYPE_CLASS_FULL_NAME); ocr.setTarget(LookupUtil.lookupObjectClass(an)); an.setName(event.getChildClassName()); ocr.setSource(LookupUtil.lookupObjectClass(an)); ocr.setType(ObjectClassRelationship.TYPE_IS); // Inherit all attributes // Find all DECs: ObjectClass parentOc = ocr.getTarget(), childOc = ocr.getSource(); if(childOc == null || parentOc == null) { logger.warn("Skipping generalization because parent or child can't be found. Did you filter out some classes?"); return; } List newElts = new ArrayList(); List<DataElement> des = elements.getElements(DomainObjectFactory.newDataElement()); if(des != null) for(DataElement de : des) { DataElementConcept dec = de.getDataElementConcept(); if(dec.getObjectClass() == parentOc) { DataElementConcept newDec = DomainObjectFactory.newDataElementConcept(); newDec.setProperty(dec.getProperty()); newDec.setObjectClass(childOc); // for(Definition def : dec.getDefinitions()) { // newDec.addDefinition(def); String propName = newDec.getProperty().getLongName(); String s = event.getChildClassName(); int ind = s.lastIndexOf("."); String className = s.substring(ind + 1); String packageName = s.substring(0, ind); newDec.setLongName(className + ":" + propName); DataElement newDe = DomainObjectFactory.newDataElement(); newDe.setDataElementConcept(newDec); newDe.setLongName(newDec.getLongName() + " " + de.getValueDomain().getLongName()); // check existing de mapping IdVersionPair deIdVersionPair = event.getPersistenceMapping(propName); if(deIdVersionPair != null) { DataElement existingDe = findExistingDe(deIdVersionPair.getId(), deIdVersionPair.getVersion(), newDe, className, propName); if(existingDe != null) { mapToExistingDE(childOc, newDe, existingDe, className, propName); } } if(newDe.getPublicId() == null) { // check local VD mapping String localType = event.getDatatypeMapping(propName); if(localType != null) { ValueDomain vd = DomainObjectFactory.newValueDomain(); vd.setLongName(localType); newDe.setValueDomain(vd); } else { // check existing vd mapping IdVersionPair vdIdVersionPair = event.getTypeMapping(propName); if(vdIdVersionPair != null) { ValueDomain existingVd = DomainObjectFactory.newValueDomain(); populateExistingVd(existingVd, vdIdVersionPair.getId(), vdIdVersionPair.getVersion(), className + "." + propName); newDe.setValueDomain(existingVd); } else { ValueDomain newVD = DomainObjectFactory.newValueDomain(); newVD.setLongName(de.getValueDomain().getLongName()); newVD.setPublicId(de.getValueDomain().getPublicId()); newVD.setVersion(de.getValueDomain().getVersion()); newVD.setContext(de.getValueDomain().getContext()); newDe.setValueDomain(newVD); } } } Boolean isReviewed = event.getReview(propName); if(isReviewed != null) reviewTracker.put(event.getChildClassName() + "." + propName, isReviewed); // for(Definition def : de.getDefinitions()) { for(Definition def : inheritedAttributes.getTopParent(de).getDefinitions()) { if(def.getType().equals(Definition.TYPE_UML_DE)) { Definition newDef = DomainObjectFactory.newDefinition(); newDef.setType(Definition.TYPE_UML_DE); newDef.setDefinition(childOc.getPreferredDefinition() + " " + def.getDefinition()); newDe.addDefinition(newDef); } } AlternateName fullName = DomainObjectFactory.newAlternateName(); fullName.setType(AlternateName.TYPE_FULL_NAME); fullName.setName(packageName + "." + className + "." + propName); newDe.addAlternateName(fullName); // Store alt Name for DE: // ClassName:PropertyName fullName = DomainObjectFactory.newAlternateName(); fullName.setType(AlternateName.TYPE_UML_DE); fullName.setName(className + ":" + propName); newDe.addAlternateName(fullName); // for(Iterator it2 = de.getAlternateNames().iterator(); it2.hasNext();) { // AlternateName an = (AlternateName)it2.next(); // newDe.addAlternateName(an); newDe.setAcCsCsis(childOc.getAcCsCsis()); newDec.setAcCsCsis(childOc.getAcCsCsis()); Property oldProp = de.getDataElementConcept().getProperty(); List oldAcCsCsis = oldProp.getAcCsCsis(); List newAcCsCsis = new ArrayList(childOc.getAcCsCsis()); newAcCsCsis.addAll(oldAcCsCsis); oldProp.setAcCsCsis(newAcCsCsis); // newElts.add(newProp); newElts.add(newDe); newElts.add(newDec); inheritedAttributes.add(newDe, de); } } for(Iterator it = newElts.iterator(); it.hasNext(); elements.addElement(it.next())); elements.addElement(ocr); logger.debug("Generalization: "); logger.debug("Source:"); logger.debug("-- " + ocr.getSource().getLongName()); logger.debug("Target: "); if(ocr.getTarget() != null) logger.debug("-- " + ocr.getTarget().getLongName()); else { logger.error("Target does not exist: "); logger.error("Parent: " + event.getParentClassName()); } } private Concept newConcept(NewConceptEvent event) { Concept concept = DomainObjectFactory.newConcept(); concept.setPreferredName(event.getConceptCode()); concept.setPreferredDefinition(event.getConceptDefinition()); concept.setDefinitionSource(event.getConceptDefinitionSource()); concept.setLongName(event.getConceptPreferredName()); elements.addElement(concept); return concept; } private List<Concept> createConcepts(NewConceptualEvent event) { List<Concept> concepts = new ArrayList<Concept>(); List<NewConceptEvent> conEvs = event.getConcepts(); for(NewConceptEvent conEv : conEvs) { concepts.add(newConcept(conEv)); } return concepts; } // private void verifyConcepts(AdminComponent cause, List concepts) { // for(Iterator it = concepts.iterator(); it.hasNext(); ) { // Concept concept = (Concept)it.next(); // if(StringUtil.isEmpty(concept.getPreferredName())) { // ValidationItems.getInstance() // .addItem(new ValidationError( // PropertyAccessor.getProperty("validation.concept.missing.for", cause.getLongName()), // cause)); //// elements.addElement(new ConceptError( //// ConceptError.SEVERITY_ERROR, //// PropertyAccessor.getProperty("validation.concept.missing.for", eltName))); public void setCadsrModule(CadsrModule module) { this.cadsrModule = module; } public void beginParsing() {} public void endParsing() {} public void addProgressListener(ProgressListener listener) {} }
package io.craigmiller160.locus.util; public class LocusScannerFactory { public LocusScannerFactory() { } /** * Get a new instance of this factory class. * * @return a new instance of LocusScannerFactory. */ public static LocusScannerFactory newInstance() { return new LocusScannerFactory(); } public LocusScanner newLocusScanner(){ return new LocusScannerImpl(); } }
package gov.nih.nci.ncicb.cadsr.loader.ui; import gov.nih.nci.ncicb.cadsr.domain.ClassificationScheme; import gov.nih.nci.ncicb.cadsr.domain.Representation; import gov.nih.nci.ncicb.cadsr.domain.ConceptualDomain; import gov.nih.nci.ncicb.cadsr.domain.DomainObjectFactory; import gov.nih.nci.ncicb.cadsr.domain.ValueDomain; import gov.nih.nci.ncicb.cadsr.loader.UserSelections; import gov.nih.nci.ncicb.cadsr.loader.event.ElementChangeEvent; import gov.nih.nci.ncicb.cadsr.loader.event.ElementChangeListener; import gov.nih.nci.ncicb.cadsr.loader.ext.CadsrModule; import gov.nih.nci.ncicb.cadsr.loader.ext.CadsrModuleListener; import gov.nih.nci.ncicb.cadsr.loader.ui.tree.UMLNode; import gov.nih.nci.ncicb.cadsr.loader.ui.tree.ValueDomainNode; import java.awt.*; import java.awt.event.ItemEvent; import javax.swing.*; import gov.nih.nci.ncicb.cadsr.loader.ui.util.UIUtil; import gov.nih.nci.ncicb.cadsr.loader.util.ConventionUtil; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.ItemListener; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; import java.util.List; import javax.swing.event.DocumentEvent; import javax.swing.event.DocumentListener; public class ValueDomainViewPanel extends JPanel implements Editable, CadsrModuleListener, ItemListener, DocumentListener { private JLabel vdPrefDefTitleLabel = new JLabel("VD Preferred Definition"), vdDatatypeTitleLabel = new JLabel("VD Datatype"), vdTypeTitleLabel = new JLabel("VD Type"), vdCdIdTitleLabel = new JLabel("VD CD PublicId / Version"), vdRepIdTitleLabel = new JLabel("Representation PublicId / Version"), vdCdLongNameTitleLabel = new JLabel("VD CD Long Name"); private JTextArea vdPrefDefValueTextField = new JTextArea(); private CadsrDialog cadsrCDDialog; private CadsrDialog cadsrREPDialog; private JComboBox vdDatatypeValueCombobox = null; private JRadioButton vdTypeERadioButton = new JRadioButton("E"); private JRadioButton vdTypeNRadioButton = new JRadioButton("N"); private JRadioButton tmpInvisible = new JRadioButton("dummy"); private ButtonGroup vdTypeRadioButtonGroup = new ButtonGroup(); private JLabel vdCDPublicIdJLabel = null; private JLabel vdCdLongNameValueJLabel = null; private JButton searchButton = new JButton("Search"); private JButton repSearchButton = new JButton("Search"); private JLabel vdRepIdValueJLabel = null; private JScrollPane scrollPane; private List datatypeList = null; private ValueDomain vd, tempVD; private ApplyButtonPanel applyButtonPanel; private UMLNode umlNode; private CadsrModule cadsrModule; private boolean isInitialized = false; private List<ElementChangeListener> changeListeners = new ArrayList<ElementChangeListener>(); private List<PropertyChangeListener> propChangeListeners = new ArrayList<PropertyChangeListener>(); public void addPropertyChangeListener(PropertyChangeListener l) { super.addPropertyChangeListener(l);; propChangeListeners.add(l); } public ValueDomainViewPanel() { } public void update(ValueDomain vd, UMLNode umlNode) { this.vd = vd; this.umlNode = umlNode; tempVD = DomainObjectFactory.newValueDomain(); tempVD.setConceptualDomain(vd.getConceptualDomain()); tempVD.setPreferredDefinition(vd.getPreferredDefinition()); tempVD.setRepresentation(vd.getRepresentation()); tempVD.setDataType(vd.getDataType()); tempVD.setVdType(vd.getVdType()); vd = null; if(!isInitialized) initUI(); initValues(); applyButtonPanel.propertyChange(new PropertyChangeEvent(this, ButtonPanel.SETUP, null, true)); applyButtonPanel.update(); } private void initUI() { isInitialized = true; this.setLayout(new BorderLayout()); JPanel mainPanel = new JPanel(new GridBagLayout()); applyButtonPanel = new ApplyButtonPanel(this, (ValueDomainNode)umlNode); addPropertyChangeListener(applyButtonPanel); this.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); populateDatatypeCombobox(); this.setCursor(Cursor.getDefaultCursor()); JPanel vdTypeRadioButtonPanel = new JPanel(new FlowLayout(FlowLayout.LEFT)); vdTypeRadioButtonGroup.add(vdTypeERadioButton); vdTypeRadioButtonGroup.add(vdTypeNRadioButton); vdTypeRadioButtonGroup.add(tmpInvisible); vdTypeRadioButtonPanel.add(vdTypeERadioButton); vdTypeRadioButtonPanel.add(vdTypeNRadioButton); vdTypeRadioButtonPanel.add(tmpInvisible); tmpInvisible.setVisible(false); JPanel vdCDIdVersionPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT)); vdCDPublicIdJLabel = new JLabel(); vdCDIdVersionPanel.add(vdCDPublicIdJLabel); vdCDIdVersionPanel.add(searchButton); searchButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent evt) { cadsrCDDialog.setAlwaysOnTop(true); cadsrCDDialog.setVisible(true); ConceptualDomain cd = (ConceptualDomain)cadsrCDDialog.getAdminComponent(); if(cd == null) return; tempVD.setConceptualDomain(cd); //initValues(); setVdCdSearchedValues(); firePropertyChangeEvent(new PropertyChangeEvent(this, ApplyButtonPanel.SAVE, null, true)); }}); repSearchButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent evt) { cadsrREPDialog.setAlwaysOnTop(true); cadsrREPDialog.setVisible(true); Representation rep = (Representation)cadsrREPDialog.getAdminComponent(); if(rep == null) return; tempVD.setRepresentation(rep); //initValues(); setRepSearchedValues(); firePropertyChangeEvent(new PropertyChangeEvent(this, ApplyButtonPanel.SAVE, null, true)); }}); vdCdLongNameValueJLabel = new JLabel(); JPanel vdCDRepPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT)); vdRepIdValueJLabel = new JLabel(); vdCDRepPanel.add(vdRepIdValueJLabel); vdCDRepPanel.add(repSearchButton); vdPrefDefValueTextField.setLineWrap(true); vdPrefDefValueTextField.setWrapStyleWord(true); scrollPane = new JScrollPane(vdPrefDefValueTextField); scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS); scrollPane = new JScrollPane(vdPrefDefValueTextField); scrollPane.setPreferredSize(new Dimension(200, 100)); UIUtil.insertInBag(mainPanel, vdPrefDefTitleLabel, 0, 1); UIUtil.insertInBag(mainPanel, scrollPane, 1, 1, 3, 1); UIUtil.insertInBag(mainPanel, vdDatatypeTitleLabel, 0, 3); UIUtil.insertInBag(mainPanel, vdDatatypeValueCombobox, 1, 3); UIUtil.insertInBag(mainPanel, vdTypeTitleLabel, 0, 4); UIUtil.insertInBag(mainPanel, vdTypeRadioButtonPanel, 1, 4); UIUtil.insertInBag(mainPanel, vdCdIdTitleLabel, 0, 5); UIUtil.insertInBag(mainPanel, vdCDIdVersionPanel, 1, 5); UIUtil.insertInBag(mainPanel, vdCdLongNameTitleLabel, 0, 6); UIUtil.insertInBag(mainPanel, vdCdLongNameValueJLabel, 1, 6); UIUtil.insertInBag(mainPanel, vdRepIdTitleLabel, 0, 7); UIUtil.insertInBag(mainPanel, vdCDRepPanel, 1, 7); JScrollPane scrollPane = new JScrollPane(mainPanel); scrollPane.getVerticalScrollBar().setUnitIncrement(30); this.add(scrollPane, BorderLayout.CENTER); } private void initValues() { vdPrefDefValueTextField.setText(tempVD.getPreferredDefinition()); int datatypeIndex = tempVD.getDataType() == null ? -1 : getSelectedIndex(tempVD.getDataType()); vdDatatypeValueCombobox.setSelectedIndex(datatypeIndex == -1 ? 0 : datatypeIndex); if(vd.getVdType() != null){ if(!vd.getVdType().equals("null")){ if(!vd.getVdType().equals(null)){ if(tempVD.getVdType().equals("E")){ vdTypeERadioButton.setSelected(true); vdTypeNRadioButton.setSelected(false); } else if(tempVD.getVdType().equals("N")){ vdTypeNRadioButton.setSelected(true); vdTypeERadioButton.setSelected(false); } }else{ tmpInvisible.setSelected(true); vdTypeERadioButton.setSelected(false); vdTypeNRadioButton.setSelected(false); } }else{ tmpInvisible.setSelected(true); vdTypeERadioButton.setSelected(false); vdTypeNRadioButton.setSelected(false); } }else{ tmpInvisible.setSelected(true); vdTypeERadioButton.setSelected(false); vdTypeNRadioButton.setSelected(false); } vdCDPublicIdJLabel.setText(ConventionUtil.publicIdVersion(tempVD.getConceptualDomain())); if(tempVD.getConceptualDomain().getLongName() != null && !tempVD.getConceptualDomain().getLongName().equals("")) vdCdLongNameValueJLabel.setText(tempVD.getConceptualDomain().getLongName()); else vdCdLongNameValueJLabel.setText("Unable to lookup CD Long Name"); vdRepIdValueJLabel.setText(ConventionUtil.publicIdVersion(tempVD.getRepresentation())); firePropertyChangeEvent(new PropertyChangeEvent(this, ApplyButtonPanel.SAVE, null, false)); vdPrefDefValueTextField.getDocument().addDocumentListener(this); vdTypeERadioButton.addItemListener(this); vdTypeNRadioButton.addItemListener(this); vdDatatypeValueCombobox.addItemListener(this); } private void setVdCdSearchedValues(){ vdCDPublicIdJLabel.setText(ConventionUtil.publicIdVersion(tempVD.getConceptualDomain())); if(tempVD.getConceptualDomain().getLongName() != null && !tempVD.getConceptualDomain().getLongName().equals("")) vdCdLongNameValueJLabel.setText(tempVD.getConceptualDomain().getLongName()); else vdCdLongNameValueJLabel.setText("Unable to lookup CD Long Name"); } private void setRepSearchedValues(){ vdRepIdValueJLabel.setText(ConventionUtil.publicIdVersion(tempVD.getRepresentation())); } public static void main(String args[]) { // JFrame frame = new JFrame(); // ValueDomainViewPanel vdPanel = new ValueDomainViewPanel(); // vdPanel.setVisible(true); // frame.add(vdPanel); // frame.setVisible(true); // frame.setSize(450, 350); } public void applyPressed() { vd.setPublicId(null); vd.setConceptualDomain(tempVD.getConceptualDomain()); vd.setRepresentation(tempVD.getRepresentation()); if(vdDatatypeValueCombobox.getSelectedIndex() != 0){ vd.setDataType(String.valueOf(vdDatatypeValueCombobox.getSelectedItem()));} if(vdPrefDefValueTextField.getText() != null || !vdPrefDefValueTextField.getText().equals("null") || vdPrefDefValueTextField.getText().length() > 0) vd.setPreferredDefinition(vdPrefDefValueTextField.getText()); if(vdTypeERadioButton.isSelected()) vd.setVdType("E"); if(vdTypeNRadioButton.isSelected()) vd.setVdType("N"); vdTypeERadioButton.addItemListener(this); vdTypeNRadioButton.addItemListener(this); firePropertyChangeEvent(new PropertyChangeEvent(this, ApplyButtonPanel.SAVE, null, false)); fireElementChangeEvent(new ElementChangeEvent(umlNode)); } public void setCadsrCDDialog(CadsrDialog cadsrCDDialog) { this.cadsrCDDialog = cadsrCDDialog; } public void setCadsrREPDialog(CadsrDialog cadsrREPDialog) { this.cadsrREPDialog = cadsrREPDialog; } public void setCadsrModule(CadsrModule cadsrModule){ this.cadsrModule = cadsrModule; } private void populateDatatypeCombobox(){ datatypeList = new ArrayList(); Collection<String> collDatatypes = cadsrModule.getAllDatatypes(); vdDatatypeValueCombobox = new JComboBox(); vdDatatypeValueCombobox.addItem("Please Select The Datatype"); datatypeList.add("Please Select The Datatype"); Iterator itr = collDatatypes.iterator(); while(itr.hasNext()){ String datatypeValue = (String) itr.next(); datatypeList.add(datatypeValue); vdDatatypeValueCombobox.addItem(datatypeValue); } } private int getSelectedIndex(String selectedString){ for(int i=0; i<datatypeList.size(); i++) if(datatypeList.get(i)!= null && datatypeList.get(i).toString().trim().equals(selectedString.trim())) return i; return -1; } public void addElementChangeListener(ElementChangeListener listener){ changeListeners.add(listener); } private void fireElementChangeEvent(ElementChangeEvent event) { for(ElementChangeListener l : changeListeners) l.elementChanged(event); } private void firePropertyChangeEvent(PropertyChangeEvent evt) { for(PropertyChangeListener l : propChangeListeners) l.propertyChange(evt); } public void itemStateChanged(ItemEvent e) { firePropertyChangeEvent(new PropertyChangeEvent(this, ApplyButtonPanel.SAVE, null, true)); } public void insertUpdate(DocumentEvent e) { firePropertyChangeEvent(new PropertyChangeEvent(this, ApplyButtonPanel.SAVE, null, true)); } public void removeUpdate(DocumentEvent e) { firePropertyChangeEvent(new PropertyChangeEvent(this, ApplyButtonPanel.SAVE, null, true)); } public void changedUpdate(DocumentEvent e) { firePropertyChangeEvent(new PropertyChangeEvent(this, ApplyButtonPanel.SAVE, null, true)); } public UMLNode getNode() { return umlNode; } }
package io.starter.ignite.security.dao; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.Properties; import javax.naming.InitialContext; import javax.sql.DataSource; import org.apache.tomcat.jdbc.pool.PoolExhaustedException; import org.apache.tomcat.jdbc.pool.PoolProperties; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import io.starter.ignite.generator.Configuration; import io.starter.ignite.util.SystemConstants; /** * * get connections using MyBatisConfig.xml settings * * @version 1.5 */ public class ConnectionFactory { protected static final Logger logger = LoggerFactory.getLogger(ConnectionFactory.class); // Connect to the data storage private static int sourcePort = 3306; private static String driverName = SystemConstants.dbDriver; private static String dbName = SystemConstants.dbName; private static String sourceURL = SystemConstants.dbUrl; private static String userName = SystemConstants.dbUser; private static String password = SystemConstants.dbPassword; private static String backupURL = SystemConstants.dbUrl; private static String backupPassword = SystemConstants.dbPassword; private static DataSource dsx = null; // Call the private constructor to initialize the // DriverManager @SuppressWarnings("unused") public static ConnectionFactory instance = new ConnectionFactory(); public static String toConfigString() { return "ConnectionFactory v." + SystemConstants.IGNITE_MAJOR_VERSION + "." + SystemConstants.IGNITE_MINOR_VERSION + Configuration.LINE_FEED + "Settings:" + Configuration.LINE_FEED + "=========" + Configuration.LINE_FEED + ConnectionFactory.driverName + Configuration.LINE_FEED + ConnectionFactory.sourceURL + Configuration.LINE_FEED + ConnectionFactory.dbName + Configuration.LINE_FEED + ConnectionFactory.userName; } /** * Private default constructor No outside objects can create an object of this * class This constructor initializes the DriverManager by loading the driver * for the database */ private ConnectionFactory() { ConnectionFactory.logger.info("ConnectionFactory: initializing:" + ConnectionFactory.driverName); try { Class.forName(ConnectionFactory.driverName); ConnectionFactory.logger.info("ConnectionFactory: Got JDBC class " + ConnectionFactory.driverName + " OK!"); } catch (final ClassNotFoundException e) { ConnectionFactory.logger.error("ConnectionFactory: Exception loading driver class: " + e.toString()); } // end try-catch } // end default private constructor /** * Get and return a Connection object that can be used to connect to the data * storage * * @return Connection * @throws SQLException */ public static Connection getConnection() throws SQLException { try { Connection cx = getDataSource().getConnection(); if (!cx.isValid(5000)) { dsx = null; cx = DriverManager.getConnection(ConnectionFactory.sourceURL + "/" + ConnectionFactory.dbName + "?" + "user=" + ConnectionFactory.userName + "&password=" + ConnectionFactory.password); } return cx; }catch(PoolExhaustedException x) { dsx = null; dsx = getDataSource(); return dsx.getConnection(); } } /** * wrap a datasource with a tomcat jdbc pool Connection con = null; * * TODO: implement FUTURE connections try { Future<Connection> future = * datasource.getConnectionAsync(); while (!future.isDone()) { logger.info( * "Connection is not yet available. Do some background work"); try { * Thread.sleep(100); //simulate work }catch (InterruptedException x) { * Thread.currentThread().interrupt(); } } con = future.get(); //should return * instantly Statement st = con.createStatement(); ResultSet rs = * st.executeQuery("select * from user"); * * @return */ public static DataSource getDataSource() { if (dsx != null) { return dsx; } else { dsx = new org.apache.tomcat.jdbc.pool.DataSource(); } final PoolProperties p = new PoolProperties(); String lcname = System.getProperty("PARAM1"); if (lcname != null) { if (lcname.equalsIgnoreCase("production")) { lcname = SystemConstants.JNDI_DB_LOOKUP_STRING; } else if (lcname.equalsIgnoreCase("staging")) { lcname = SystemConstants.JNDI_DB_LOOKUP_STRING + "_staging"; } try { final InitialContext ic = new InitialContext(); final DataSource dataSource = (DataSource) ic.lookup(lcname); final java.sql.Connection c = dataSource.getConnection(); ConnectionFactory.logger.info("ConnectionFactory.getConnection() SUCCESSFUL JNDI connection: " + lcname + ": connection ready: " + !c.isClosed()); return dataSource; } catch (final Exception e) { ConnectionFactory.logger.info("ConnectionFactory.getConnection() failed to get JNDI connection: " + lcname + ". " + e.toString() + " Falling back to non JNDI connection."); ((org.apache.tomcat.jdbc.pool.DataSource) dsx) .setUrl(ConnectionFactory.sourceURL + "/" + ConnectionFactory.dbName); ((org.apache.tomcat.jdbc.pool.DataSource) dsx).setPassword(ConnectionFactory.password); p.setUrl(ConnectionFactory.sourceURL + "/" + ConnectionFactory.dbName); } } else { ((org.apache.tomcat.jdbc.pool.DataSource) dsx) .setUrl(ConnectionFactory.backupURL + "/" + ConnectionFactory.dbName); ((org.apache.tomcat.jdbc.pool.DataSource) dsx).setPassword(ConnectionFactory.backupPassword); p.setUrl(ConnectionFactory.backupURL + "/" + ConnectionFactory.dbName); p.setPassword(ConnectionFactory.backupPassword); } // dsx.setPort(ConnectionFactory.sourcePort); final Properties dbProperties = new Properties(); dbProperties.put("dbName", ConnectionFactory.dbName); dbProperties.put("port", ConnectionFactory.sourcePort); ((org.apache.tomcat.jdbc.pool.DataSource) dsx).setDbProperties(dbProperties); ((org.apache.tomcat.jdbc.pool.DataSource) dsx).setUsername(ConnectionFactory.userName); p.setDriverClassName(driverName); p.setUsername(ConnectionFactory.userName); p.setJmxEnabled(true); // p.setTestWhileIdle(false); // p.setTestOnBorrow(true); p.setValidationQuery("SELECT 1"); // p.setTestOnReturn(false); // p.setValidationInterval(30000); // p.setTimeBetweenEvictionRunsMillis(5000); p.setMaxActive(100); p.setInitialSize(10); // p.setMaxWait(10000); // p.setLogAbandoned(false); // p.setRemoveAbandoned(true); // p.setRemoveAbandonedTimeout(600); // p.setMinEvictableIdleTimeMillis(60000); // p.setMinIdle(10); // crucial to avoid abandoned PooledConnection errors. p.setJdbcInterceptors("org.apache.tomcat.jdbc.pool.interceptor.ConnectionState;" + "org.apache.tomcat.jdbc.pool.interceptor.StatementFinalizer;" + "org.apache.tomcat.jdbc.pool.interceptor.ResetAbandonedTimer"); // wrap and allow for lazy queue fun ((org.apache.tomcat.jdbc.pool.DataSource) dsx).setPoolProperties(p); ((org.apache.tomcat.jdbc.pool.DataSource) dsx).setFairQueue(true); // dsx.setDataSource(dsx); return dsx; } /** * Close the ResultSet * * @param rs ResultSet */ public static void close(ResultSet rs) { try { rs.close(); } catch (final SQLException e) { ConnectionFactory.logger.error("ERROR: Unable to close Result Set"); ConnectionFactory.logger.error(e.getMessage()); } // end try-catch block } // end method close /** * Close statement object * * @param stmt Statement */ public static void close(Statement stmt) { try { stmt.close(); } catch (final SQLException e) { ConnectionFactory.logger.error("ERROR: Unable to close Statement"); ConnectionFactory.logger.error(e.getMessage()); } // end try-catch block } // end method close /** * Close connection * * @param conn Connection */ public static void close(Connection conn) { try { conn.close(); conn = null; } catch (final SQLException e) { ConnectionFactory.logger.info("ERROR: Unable to close Statement"); ConnectionFactory.logger.info(e.getMessage()); } // end try-catch block } // end method close public void setDataSource(DataSource dataSource) { dsx = dataSource; } } // end class ConnectionFactory
package jitk.spline; import java.util.Arrays; import org.apache.log4j.LogManager; import org.apache.log4j.Logger; import org.ejml.data.DenseMatrix64F; import org.ejml.factory.LinearSolver; import org.ejml.factory.LinearSolverFactory; import org.ejml.ops.CommonOps; import org.ejml.ops.NormOps; import mpicbg.models.CoordinateTransform; public class ThinPlateR2LogRSplineKernelTransform implements CoordinateTransform { private static final long serialVersionUID = -972934724062617822L; protected final int ndims; protected DenseMatrix64F dMatrix; protected double[][] aMatrix; protected double[] bVector; protected double stiffness = 0.0; // reasonable values take the range [0.0, 0.5] protected boolean wMatrixComputeD = false; protected boolean computeAffine = true; protected int nLandmarks; protected final double[][] sourceLandmarks; protected double[] weights; // TODO: make the weights do something :-P protected static final double EPS = 1e-8; protected static Logger logger = LogManager.getLogger( ThinPlateR2LogRSplineKernelTransform.class.getName() ); /* * Constructs an identity thin plate spline transform */ public ThinPlateR2LogRSplineKernelTransform( final int ndims ) { this.ndims = ndims; sourceLandmarks = null; nLandmarks = 0; } public ThinPlateR2LogRSplineKernelTransform( final int ndims, final double[][] srcPts, final double[][] tgtPts ) { this( ndims, srcPts, tgtPts, true ); } public ThinPlateR2LogRSplineKernelTransform( final int ndims, final float[][] srcPts, final float[][] tgtPts ) { this( ndims, srcPts, tgtPts, true ); } /* * Constructor with point matches */ public ThinPlateR2LogRSplineKernelTransform( final int ndims, final double[][] srcPts, final double[][] tgtPts, boolean computeAffine ) { this.ndims = ndims; this.sourceLandmarks = srcPts; this.computeAffine = computeAffine; if ( sourceLandmarks != null && sourceLandmarks.length > 0 ) nLandmarks = srcPts[ 0 ].length; else nLandmarks = 0; computeW( buildDisplacements( tgtPts ) ); } /* * Constructor with point matches */ public ThinPlateR2LogRSplineKernelTransform( final int ndims, final float[][] srcPts, final float[][] tgtPts, boolean computeAffine ) { this.ndims = ndims; this.computeAffine = computeAffine; sourceLandmarks = new double[ ndims ][ nLandmarks ]; if ( sourceLandmarks != null && sourceLandmarks.length > 0 ) nLandmarks = srcPts[ 0 ].length; else nLandmarks = 0; for ( int i = 0; i < nLandmarks; ++i ) { for ( int d = 0; d < ndims; ++d ) { sourceLandmarks[ d ][ i ] = srcPts[ d ][ i ]; } } computeW( buildDisplacements( tgtPts ) ); } /* * Constructor with weighted point matches */ public ThinPlateR2LogRSplineKernelTransform( final int ndims, final double[][] srcPts, final double[][] tgtPts, final double[] weights ) { this( ndims, srcPts, tgtPts ); setWeights( weights ); } /** * Constructor with transformation parameters. aMatrix and bVector are * allowed to be null */ public ThinPlateR2LogRSplineKernelTransform( final double[][] srcPts, final double[][] aMatrix, final double[] bVector, final double[] dMatrixData ) { ndims = srcPts.length; if ( srcPts != null && srcPts.length > 0 ) nLandmarks = srcPts[ 0 ].length; else nLandmarks = 0; this.sourceLandmarks = srcPts; this.aMatrix = aMatrix; this.bVector = bVector; dMatrix = new DenseMatrix64F( ndims, nLandmarks ); dMatrix.setData( dMatrixData ); } public int getNumLandmarks() { return this.nLandmarks; } public int getNumDims() { return ndims; } public double[][] getSourceLandmarks() { return sourceLandmarks; } public double[][] getAffine() { return aMatrix; } public double[] getTranslation() { return bVector; } public double[] getKnotWeights() { return dMatrix.getData(); } /** * Sets the weights. Checks that the length matches the number of landmarks. */ private void setWeights( final double[] weights ) { // make sure the length matches number // of landmarks if ( weights == null ) { return; } if ( weights.length != this.nLandmarks ) { this.weights = weights; } else { logger.error( "weights have length (" + weights.length + ") but tmust have length equal to number of landmarks " + this.nLandmarks ); } } public void setDoAffine( final boolean estimateAffine ) { this.computeAffine = estimateAffine; } protected DenseMatrix64F computeReflexiveG() { DenseMatrix64F gMatrix = new DenseMatrix64F( ndims, ndims ); CommonOps.fill( gMatrix, 0 ); for ( int i = 0; i < ndims; i++ ) { gMatrix.set( i, i, stiffness ); } return gMatrix; } protected double normSqrd( final double[] v ) { double nrm = 0; for ( int i = 0; i < v.length; i++ ) { nrm += v[ i ] * v[ i ]; } return nrm; } public DenseMatrix64F buildDisplacements( double[][] targetLandmarks ) { DenseMatrix64F yMatrix; if ( computeAffine ) yMatrix = new DenseMatrix64F( ndims * (nLandmarks + ndims + 1), 1 ); else yMatrix = new DenseMatrix64F( ndims * nLandmarks, 1 ); // for (int i = 0; i < nLandmarks; i++) { int i = 0; while ( i < nLandmarks ) { for ( int j = 0; j < ndims; j++ ) { yMatrix.set( i * ndims + j, 0, (targetLandmarks[ j ][ i ] - sourceLandmarks[ j ][ i ]) ); } i++; } if ( computeAffine ) { for ( i = 0; i < ndims * (ndims + 1); i++ ) { yMatrix.set( nLandmarks * ndims + i, 0, 0 ); } } return yMatrix; } public DenseMatrix64F buildDisplacements( float[][] targetLandmarks ) { DenseMatrix64F yMatrix; if ( computeAffine ) yMatrix = new DenseMatrix64F( ndims * (nLandmarks + ndims + 1), 1 ); else yMatrix = new DenseMatrix64F( ndims * nLandmarks, 1 ); // for (int i = 0; i < nLandmarks; i++) { int i = 0; while ( i < nLandmarks ) { for ( int j = 0; j < ndims; j++ ) { yMatrix.set( i * ndims + j, 0, (targetLandmarks[ j ][ i ] - sourceLandmarks[ j ][ i ]) ); } i++; } if ( computeAffine ) { for ( i = 0; i < ndims * (ndims + 1); i++ ) { yMatrix.set( nLandmarks * ndims + i, 0, 0 ); } } return yMatrix; } /** * The main workhorse method. * <p> * Implements Equation (5) in Davis et al. and calls reorganizeW. * */ protected void computeW( final DenseMatrix64F yMatrix ) { final DenseMatrix64F kMatrix; final DenseMatrix64F pMatrix; final DenseMatrix64F wMatrix; /** * INITIALIZE MATRICES */ dMatrix = new DenseMatrix64F( ndims, nLandmarks ); kMatrix = new DenseMatrix64F( ndims * nLandmarks, ndims * nLandmarks ); if ( computeAffine ) { aMatrix = new double[ ndims ][ ndims ]; bVector = new double[ ndims ]; pMatrix = new DenseMatrix64F( ( ndims * nLandmarks ), ( ndims * ( ndims + 1 ) ) ); wMatrix = new DenseMatrix64F( ( ndims * nLandmarks ) + ndims * ( ndims + 1 ), 1 ); } else { // we dont need the P matrix and L can point // directly to K rather than itself being initialized // the W matrix won't hold the affine component wMatrix = new DenseMatrix64F( ndims * nLandmarks, 1 ); pMatrix = null; } // gMatrix = new DenseMatrix64F( ndims, ndims ); final DenseMatrix64F lMatrix = computeL( kMatrix, pMatrix ); final LinearSolver< DenseMatrix64F > solver; if ( nLandmarks < ndims * ndims ) { logger.debug( "pseudo inverse solver" ); solver = LinearSolverFactory.pseudoInverse( false ); } else { logger.debug( "linear solver" ); solver = LinearSolverFactory.linear( lMatrix.numCols ); } // solve linear system solver.setA( lMatrix ); solver.solve( yMatrix, wMatrix ); reorganizeW( wMatrix ); } protected DenseMatrix64F computeL(DenseMatrix64F kMatrix, DenseMatrix64F pMatrix) { computeK( kMatrix ); // fill P matrix if the affine parameters need to be computed if ( computeAffine ) { computeP( pMatrix ); DenseMatrix64F lMatrix = new DenseMatrix64F( ndims * ( nLandmarks + ndims + 1 ), ndims * ( nLandmarks + ndims + 1 ) ); CommonOps.insert( kMatrix, lMatrix, 0, 0 ); CommonOps.insert( pMatrix, lMatrix, 0, kMatrix.getNumCols() ); CommonOps.transpose( pMatrix ); CommonOps.insert( pMatrix, lMatrix, kMatrix.getNumRows(), 0 ); CommonOps.insert( kMatrix, lMatrix, 0, 0 ); // P matrix should be zero if points are already affinely aligned // bottom left O2 is already zeros after initializing 'lMatrix' return lMatrix; } else { // in this case the L matrix // consists only of the K block. return kMatrix; } } protected void computeP(DenseMatrix64F pMatrix) { final DenseMatrix64F tmp = new DenseMatrix64F( ndims, ndims ); final DenseMatrix64F I = new DenseMatrix64F( ndims, ndims ); CommonOps.setIdentity( I ); int i = 0; while ( i < nLandmarks ) { for ( int d = 0; d < ndims; d++ ) { CommonOps.scale( sourceLandmarks[ d ][ i ], I, tmp ); CommonOps.insert( tmp, pMatrix, i * ndims, d * ndims ); } CommonOps.insert( I, pMatrix, i * ndims, ndims * ndims ); i++; } } /** * Builds the K matrix from landmark points and G matrix. * @param kMatrix */ protected void computeK(DenseMatrix64F kMatrix) { final double[] res = new double[ ndims ]; int i = 0; final DenseMatrix64F Gbase = computeReflexiveG(); final DenseMatrix64F G = Gbase.copy(); while ( i < nLandmarks ) { CommonOps.insert( Gbase, kMatrix, i * ndims, i * ndims ); int j = i + 1; while ( j < nLandmarks ) { srcPtDisplacement( i, j, res ); computeG( res, G ); CommonOps.insert( G, kMatrix, i * ndims, j * ndims ); CommonOps.insert( G, kMatrix, j * ndims, i * ndims ); j++; } i++; } } /** * Copies data from the W matrix to the D, A, and b matrices which represent * the deformable, affine and translational portions of the transformation, * respectively. * @param wMatrix */ protected void reorganizeW (DenseMatrix64F wMatrix ) { // the deformable (non-affine) part of the transform int ci = 0; int i = 0; while ( i < nLandmarks ) { for ( int d = 0; d < ndims; d++ ) { dMatrix.set( d, i, wMatrix .get( ci, 0 ) ); ci++; } i++; } // the affine part of the transform if ( computeAffine ) { // the affine part of the transform for ( int j = 0; j < ndims; j++ ) for ( i = 0; i < ndims; i++ ) { aMatrix[ i ][ j ] = wMatrix.get( ci, 0 ); ci++; } // the translation part of the transform for ( int k = 0; k < ndims; k++ ) { bVector[ k ] = wMatrix.get( ci, 0 ); ci++; } } wMatrix = null; } public void computeG( final double[] pt, final DenseMatrix64F mtx ) { final double r = Math.sqrt( normSqrd( pt ) ); final double nrm = r2Logr( r ); CommonOps.setIdentity( mtx ); CommonOps.scale( nrm, mtx ); } public void computeG( final double[] pt, final DenseMatrix64F mtx, final double w ) { computeG( pt, mtx ); CommonOps.scale( w, mtx ); } public void computeDeformationContribution( final double[] thispt, final double[] result ) { final double[] tmpDisplacement = new double[ ndims ]; for ( int i = 0; i < ndims; ++i ) { result[ i ] = 0; tmpDisplacement[ i ] = 0; } int di = 0; for ( int lnd = 0; lnd < nLandmarks; lnd++ ) { srcPtDisplacement( lnd, thispt, tmpDisplacement ); final double nrm = r2Logr( Math.sqrt( normSqrd( tmpDisplacement ) ) ); for ( int d = 0; d < ndims; d++ ) result[ d ] += nrm * dMatrix.get( d, di ); di++; } } /** * The derivative of component j of the output point, with respect to x_d * (the dth component of the vector) is: * * \sum_i D[ d, l ] G'( r ) ( x_j - l_ij ) / ( sqrt( N_l(p) )) * * where: D is the D matrix i indexes the landmarks N_l(p) is the squared * euclidean norm between landmark l and point p l_ij is the jth component * of landmark i G' is the derivative of the kernel function. for a TPS, the * kernel function is (r^2)logr, the derivative wrt r of which is: r( 2logr * + 1 ) * * See the documentation for a derivation. * * @param p The point at which to evaluate the derivative * @return The Jacobian matrix */ public double[][] r2LogrDerivative( final double[] p ) { // derivativeMatrix[j][d] gives the derivative of component j with // respect to component d final double[][] derivativeMatrix = new double[ ndims ][ ndims ]; final double[] tmpDisplacement = new double[ ndims ]; Arrays.fill( tmpDisplacement, 0 ); int lmi = 0; // landmark index for active points for ( int lnd = 0; lnd < nLandmarks; lnd++ ) { srcPtDisplacement( lnd, p, tmpDisplacement ); final double r2 = normSqrd( tmpDisplacement ); // squared radius final double r = Math.sqrt( r2 ); // radius // TODO if r2 is small or zero, there will be problems - put a // check in. // The check is below. // The continue statement is akin to term1 = 0.0. // This should be correct, but needs a double-checking final double term1; if ( r < EPS ) continue; else term1 = r * (2 * Math.log( r ) + 1) / Math.sqrt( r2 ); for ( int d = 0; d < ndims; d++ ) { for ( int j = 0; j < ndims; j++ ) { final double multiplier = term1 * (-tmpDisplacement[ j ]); derivativeMatrix[ j ][ d ] += multiplier * dMatrix.get( d, lmi ); } } lmi++; } return derivativeMatrix; } /** * Computes the jacobian of this tranformation around the point p. * <p> * The result is stored in a new double array where element [ i ][ j ] gives * the derivative of variable i with respect to variable j * * @param p * the point * @return the jacobian array */ public double[][] jacobian( final double[] p ) { final double[][] D = r2LogrDerivative( p ); if ( aMatrix != null ) { for ( int i = 0; i < ndims; i++ ) for ( int j = 0; j < ndims; j++ ) if ( i == j ) D[ i ][ j ] += 1 + aMatrix[ i ][ j ]; else D[ i ][ j ] += aMatrix[ i ][ j ]; } return D; } public void stepInDerivativeDirection( final double[][] derivative, final double[] start, final double[] dest, final double stepLength ) { for ( int i = 0; i < ndims; i++ ) { dest[ i ] = start[ i ]; for ( int j = 0; j < ndims; j++ ) { dest[ i ] = derivative[ i ][ j ] * stepLength; } } } public void printXfmBacks2d( final int maxx, final int maxy, final int delx, final int dely ) { final double[] pt = new double[ 2 ]; final double[] result = new double[ 2 ]; for ( int x = 0; x < maxx; x += delx ) for ( int y = 0; y < maxy; y += dely ) { pt[ 0 ] = x; pt[ 1 ] = y; this.apply( pt, result ); System.out.println( "( " + x + ", " + y + " ) -> ( " + result[ 0 ] + ", " + result[ 0 ] + " )" ); } } /** * Transforms the input point according to the affine part of the thin plate * spline stored by this object. * * @param pt * the point to be transformed * @return the transformed point */ public double[] transformPointAffine( final double[] pt ) { final double[] result = new double[ ndims ]; // affine part for ( int i = 0; i < ndims; i++ ) { for ( int j = 0; j < ndims; j++ ) { result[ i ] += aMatrix[ i ][ j ] * pt[ j ]; } } // translational part for ( int i = 0; i < ndims; i++ ) { result[ i ] += bVector[ i ] + pt[ i ]; } return result; } public void apply( final double[] pt, final double[] result ) { apply( pt, result, false ); } /** * Transform a source vector pt into a target vector result. pt and result * must NOT be the same vector. * * @param pt * @param result */ public void apply( final double[] pt, final double[] result, final boolean debug ) { if( dMatrix == null ) { for ( int j = 0; j < ndims; j++ ) result[ j ] = pt[ j ]; return; } computeDeformationContribution( pt, result ); if ( aMatrix != null ) { // affine part for ( int i = 0; i < ndims; i++ ) for ( int j = 0; j < ndims; j++ ) { result[ i ] += aMatrix[ i ][ j ] * pt[ j ]; } } else { for ( int i = 0; i < ndims; i++ ) { result[ i ] += pt[ i ]; } } if ( bVector != null ) { // translational part for ( int i = 0; i < ndims; i++ ) { result[ i ] += bVector[ i ] + pt[ i ]; } } } /** * Transforms the input point according to the thin plate spline stored by * this object. * * @param pt * the point to be transformed * @return the transformed point */ @Override public double[] apply( final double[] pt ) { final double[] result = new double[ ndims ]; apply( pt, result ); return result; } /** * Transform pt in place. * * @param pt */ @Override public void applyInPlace( final double[] pt ) { final double[] tmp = new double[ ndims ]; apply( pt, tmp ); for ( int i = 0; i < ndims; ++i ) { pt[ i ] = tmp[ i ]; } } /** * Returns the index of the target landmark closest to the input point as well * as the distance to that landmark. * * @param target the point * @return a pair containing the closest landmark point and its squared * distance to that landmark */ public IndexDistancePair closestTargetLandmarkAndDistance( final double[] target ) { int idx = -1; double distSqr = Double.MAX_VALUE; double thisDist = 0.0; final double[] err = new double[ this.ndims ]; for ( int l = 0; l < this.nLandmarks; l++ ) { tgtPtDisplacement( l, target, err ); thisDist = normSqrd( err ); if ( thisDist < distSqr ) { distSqr = thisDist; idx = l; } } return new IndexDistancePair( idx, distSqr ); } private static class IndexDistancePair { final int index; final double distance; public IndexDistancePair( final int i, final double d ) { this.index = i; this.distance = d; } } /** * Approximates the inverse of the input target point by taking the best of several * available approximation methods. * * @param target the target point * @return the approximate inverse point */ public double[] initialGuessAtInverse( final double[] target ) { final IndexDistancePair lmAndDist = closestTargetLandmarkAndDistance( target ); logger.trace( "nearest landmark error: " + lmAndDist.distance ); double[] initialGuess; final int idx = lmAndDist.index; logger.trace( "initial guess by landmark: " + idx ); initialGuess = new double[ ndims ]; for ( int i = 0; i < ndims; i++ ) initialGuess[ i ] = sourceLandmarks[ i ][ idx ]; logger.trace( "initial guess by affine " ); final double[] initialGuessAffine; if( this.aMatrix != null ) initialGuessAffine = inverseGuessAffineInv( target ); else initialGuessAffine = target; final double[] resL = apply( initialGuess ); final double[] resA = apply( initialGuessAffine ); for ( int i = 0; i < ndims; i++ ) { resL[ i ] -= target[ i ]; resA[ i ] -= target[ i ]; } final double errL = normSqrd( resL ); final double errA = normSqrd( resA ); logger.trace( "landmark guess error: " + errL ); logger.trace( "affine guess error : " + errA ); if ( errA < errL ) { logger.trace( "Using affine initialization" ); initialGuess = initialGuessAffine; } else { logger.trace( "Using landmark initialization" ); } return initialGuess; } /** * Quickly approximates the inverse of the input target point, * using the affine portion of the transform only. * * @param target a point in the target space * @return approximate inverse */ public double[] inverseGuessAffineInv( final double[] target ) { // Here, mtx is A + I final DenseMatrix64F mtx = new DenseMatrix64F( ndims + 1, ndims + 1 ); final DenseMatrix64F vec = new DenseMatrix64F( ndims + 1, 1 ); for ( int i = 0; i < ndims; i++ ) { for ( int j = 0; j < ndims; j++ ) { if ( i == j ) mtx.set( i, j, 1 + aMatrix[ i ][ j ] ); else mtx.set( i, j, aMatrix[ i ][ j ] ); } mtx.set( i, ndims, bVector[ i ] ); vec.set( i, 0, target[ i ] ); } mtx.set( ndims, ndims, 1.0 ); vec.set( ndims, 0, 1.0 ); final DenseMatrix64F res = new DenseMatrix64F( ndims + 1, 1 ); CommonOps.solve( mtx, vec, res ); final DenseMatrix64F test = new DenseMatrix64F( ndims + 1, 1 ); CommonOps.mult( mtx, res, test ); logger.trace( "test result: " + test ); final double[] resOut = new double[ ndims ]; System.arraycopy( res.data, 0, resOut, 0, ndims ); return resOut; } /** * Computes the inverse of this transformation. * * @param target the target point * @param result array in which to store the result * @param tolerance the desired precision - must be greater than zero * @param maxIters maximum number of iterations * @return true if the result is within the specified tolerance, false otherwise */ public double inverse( final double[] target, final double[] result, final double tolerance, final int maxIters ) { assert tolerance > 0.0; double[] guess = initialGuessAtInverse( target ); double error = inverseTol( target, guess, tolerance, maxIters ); for ( int d = 0; d < ndims; d++ ) result[ d ] = guess[ d ]; return error; } /** * Computes the inverse of this transformation. Performs a maximum of 100,000 iterations, * returning whatever the estimate is at that point. * * @param target the target point * @param tolerance the desired precision - must be greater than zero * @return the result of applying the inverse transform to the target point */ public double[] inverse( final double[] target, final double tolerance ) { double[] out = new double[ ndims ]; inverse( target, out, tolerance, 100000 ); return out; } public double inverseTol( final double[] target, final double[] guess, final double tolerance, final int maxIters ) { // TODO - have a flag in the apply method to also return the derivative // if requested // to prevent duplicated effort final double c = 0.0001; final double beta = 0.7; double error = 999 * tolerance; double[][] mtx; final double[] guessXfm = new double[ ndims ]; apply( guess, guessXfm ); mtx = jacobian( guess ); final TransformInverseGradientDescent inv = new TransformInverseGradientDescent( ndims, this ); inv.setTarget( target ); inv.setEstimate( guess ); inv.setEstimateXfm( guessXfm ); inv.setJacobian( mtx ); error = inv.getError(); double t0 = error; double t = 1.0; int k = 0; while ( error >= tolerance && k < maxIters ) { logger.trace( "iteration : " + k ); mtx = jacobian( guess ); inv.setJacobian( mtx ); inv.computeDirection(); logger.trace( "initial step size: " + t0 ); t = inv.backtrackingLineSearch( c, beta, 15, t0 ); logger.trace( "final step size : " + t ); if ( t == 0.0 ) break; inv.updateEstimate( t ); inv.updateError(); TransformInverseGradientDescent.copyVectorIntoArray( inv.getEstimate(), guess ); apply( guess, guessXfm ); t0 = error; inv.setEstimateXfm( guessXfm ); error = inv.getError(); logger.trace( "guess : " + XfmUtils.printArray( guess ) ); logger.trace( "guessXfm : " + XfmUtils.printArray( guessXfm ) ); logger.trace( "error vector: " + XfmUtils.printArray( inv.getErrorVector().data ) ); logger.trace( "error : " + NormOps.normP2( inv.getErrorVector() ) ); logger.trace( "abs error : " + error ); logger.trace( "" ); k++; } return error; } /** * Computes the displacement between the i^th and j^th source points. * * Stores the result in the input array 'res' Does not validate inputs. */ protected void srcPtDisplacement( final int i, final int j, final double[] res ) { for ( int d = 0; d < ndims; d++ ) { res[ d ] = sourceLandmarks[ d ][ i ] - sourceLandmarks[ d ][ j ]; } } /** * Computes the displacement between the i^th source point and the input * point. * * Stores the result in the input array 'res'. Does not validate inputs. */ protected void srcPtDisplacement( final int i, final double[] pt, final double[] res ) { for ( int d = 0; d < ndims; d++ ) { res[ d ] = sourceLandmarks[ d ][ i ] - pt[ d ]; } } /** * Computes the displacement between the i^th source point and the input * point. * * Stores the result in the input array 'res'. Does not validate inputs. */ protected void tgtPtDisplacement( final int i, final double[] pt, final double[] res ) { apply( pt, res ); for ( int d = 0; d < ndims; d++ ) { res[ d ]-= pt[ d ]; } } private static double r2Logr( final double r ) { double nrm = 0; if ( r > EPS ) { nrm = r * r * Math.log( r ); } return nrm; } }
package com.opensymphony.workflow.loader; import com.opensymphony.workflow.InvalidWorkflowDescriptorException; import com.opensymphony.workflow.util.Validatable; import org.w3c.dom.Element; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Iterator; import java.util.List; /** * @author <a href="mailto:plightbo@hotmail.com">Pat Lightbody</a> * @version $Revision: 1.15 $ */ public class ResultDescriptor extends AbstractDescriptor implements Validatable { //~ Instance fields //////////////////////////////////////////////////////// protected List postFunctions = new ArrayList(); protected List preFunctions = new ArrayList(); protected List validators = new ArrayList(); protected String displayName; protected String dueDate; protected String oldStatus; protected String owner; protected String status; protected boolean hasStep = false; protected int join; protected int split; protected int step = 0; //~ Constructors /////////////////////////////////////////////////////////// ResultDescriptor() { } ResultDescriptor(Element result) { init(result); } //~ Methods //////////////////////////////////////////////////////////////// public void setDisplayName(String displayName) { if (getParent() instanceof ActionDescriptor) { if (((ActionDescriptor) getParent()).getName().equals(displayName)) { this.displayName = null; // if displayName==parentAction.displayName, reset displayName return; } } this.displayName = displayName; } public String getDisplayName() { return displayName; } public String getDueDate() { return dueDate; } public void setJoin(int join) { this.join = join; } public int getJoin() { return join; } public void setOldStatus(String oldStatus) { this.oldStatus = oldStatus; } public String getOldStatus() { return oldStatus; } public void setOwner(String owner) { this.owner = owner; } public String getOwner() { return owner; } public List getPostFunctions() { return postFunctions; } public List getPreFunctions() { return preFunctions; } public void setSplit(int split) { this.split = split; } public int getSplit() { return split; } public void setStatus(String status) { this.status = status; } public String getStatus() { return status; } public void setStep(int step) { this.step = step; hasStep = true; } public int getStep() { return step; } public List getValidators() { return validators; } public void validate() throws InvalidWorkflowDescriptorException { ValidationHelper.validate(preFunctions); ValidationHelper.validate(postFunctions); ValidationHelper.validate(validators); //if it's not a split or a join or a finish, then we require a next step if ((split == 0) && (join == 0) && !((ActionDescriptor) getParent()).isFinish()) { StringBuffer error = new StringBuffer("Result "); if (getId() > 0) { error.append("#").append(getId()); } error.append(" is not a split or join, and has no "); if (!hasStep) { throw new InvalidWorkflowDescriptorException(error.append("next step").toString()); } if ((status == null) || (status.length() == 0)) { throw new InvalidWorkflowDescriptorException(error.append("status").toString()); } } //taken out for now //if ((split != 0) && ((join != 0) || (oldStatus.length() > 0) || (step != 0) || (status.length() > 0) || (owner.length() != 0))) { // throw new InvalidWorkflowDescriptorException("Result " + id + " has a split attribute, so should not any other attributes"); //} else if ((join != 0) && ((split != 0) || (oldStatus.length() > 0) || (step != 0) || (status.length() > 0) || (owner.length() != 0))) { // throw new InvalidWorkflowDescriptorException("Result has a join attribute, should thus not any other attributes"); //} else if ((oldStatus.length() == 0) || (step == 0) || (status.length() == 0)) { // throw new InvalidWorkflowDescriptorException("old-status, step, status and owner attributes are required if no split or join"); } public void writeXML(PrintWriter out, int indent) { XMLUtil.printIndent(out, indent++); StringBuffer buf = new StringBuffer(); buf.append("<unconditional-result"); if (hasId()) { buf.append(" id=\"").append(getId()).append("\""); } if ((dueDate != null) && (dueDate.length() > 0)) { buf.append(" due-date=\"").append(getDueDate()).append("\""); } buf.append(" old-status=\"").append(oldStatus).append("\""); if (join != 0) { buf.append(" join=\"").append(join).append("\""); } else if (split != 0) { buf.append(" split=\"").append(split).append("\""); } else { buf.append(" status=\"").append(status).append("\""); buf.append(" step=\"").append(step).append("\""); if ((owner != null) && (owner.length() > 0)) { buf.append(" owner=\"").append(owner).append("\""); } if ((displayName != null) && (displayName.length() > 0)) { buf.append(" display-name=\"").append(displayName).append("\""); } } if ((preFunctions.size() == 0) && (postFunctions.size() == 0)) { buf.append("/>"); out.println(buf.toString()); } else { buf.append(">"); out.println(buf.toString()); printPreFunctions(out, indent); printPostFunctions(out, indent); XMLUtil.printIndent(out, --indent); out.println("</unconditional-result>"); } } protected void init(Element result) { oldStatus = result.getAttribute("old-status"); status = result.getAttribute("status"); try { setId(Integer.parseInt(result.getAttribute("id"))); } catch (NumberFormatException e) { } dueDate = result.getAttribute("due-date"); try { split = Integer.parseInt(result.getAttribute("split")); } catch (Exception ex) { } try { join = Integer.parseInt(result.getAttribute("join")); } catch (Exception ex) { } try { step = Integer.parseInt(result.getAttribute("step")); hasStep = true; } catch (Exception ex) { } owner = result.getAttribute("owner"); displayName = result.getAttribute("display-name"); // set up validators -- OPTIONAL Element v = XMLUtil.getChildElement(result, "validators"); if (v != null) { List validators = XMLUtil.getChildElements(v, "validator"); for (int k = 0; k < validators.size(); k++) { Element validator = (Element) validators.get(k); ValidatorDescriptor validatorDescriptor = DescriptorFactory.getFactory().createValidatorDescriptor(validator); validatorDescriptor.setParent(this); this.validators.add(validatorDescriptor); } } // set up pre-functions -- OPTIONAL Element pre = XMLUtil.getChildElement(result, "pre-functions"); if (pre != null) { List preFunctions = XMLUtil.getChildElements(pre, "function"); for (int k = 0; k < preFunctions.size(); k++) { Element preFunction = (Element) preFunctions.get(k); FunctionDescriptor functionDescriptor = DescriptorFactory.getFactory().createFunctionDescriptor(preFunction); functionDescriptor.setParent(this); this.preFunctions.add(functionDescriptor); } } // set up post-functions - OPTIONAL Element post = XMLUtil.getChildElement(result, "post-functions"); if (post != null) { List postFunctions = XMLUtil.getChildElements(post, "function"); for (int k = 0; k < postFunctions.size(); k++) { Element postFunction = (Element) postFunctions.get(k); FunctionDescriptor functionDescriptor = DescriptorFactory.getFactory().createFunctionDescriptor(postFunction); functionDescriptor.setParent(this); this.postFunctions.add(functionDescriptor); } } } protected void printPostFunctions(PrintWriter out, int indent) { if (postFunctions.size() > 0) { XMLUtil.printIndent(out, indent++); out.println("<post-functions>"); Iterator iter = postFunctions.iterator(); while (iter.hasNext()) { FunctionDescriptor function = (FunctionDescriptor) iter.next(); function.writeXML(out, indent); } XMLUtil.printIndent(out, --indent); out.println("</post-functions>"); } } protected void printPreFunctions(PrintWriter out, int indent) { if (preFunctions.size() > 0) { XMLUtil.printIndent(out, indent++); out.println("<pre-functions>"); Iterator iter = preFunctions.iterator(); while (iter.hasNext()) { FunctionDescriptor function = (FunctionDescriptor) iter.next(); function.writeXML(out, indent); } XMLUtil.printIndent(out, --indent); out.println("</pre-functions>"); } } }
package me.lucaspickering.terraingen.render; import org.lwjgl.BufferUtils; import org.lwjgl.opengl.GL11; import org.lwjgl.stb.STBTTAlignedQuad; import org.lwjgl.stb.STBTTBakedChar; import org.lwjgl.stb.STBTruetype; import org.lwjgl.system.MemoryStack; import java.awt.Color; import java.awt.FontFormatException; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.FloatBuffer; import java.util.Arrays; import java.util.List; import java.util.Objects; import me.lucaspickering.terraingen.util.Constants; import me.lucaspickering.terraingen.util.Funcs; import me.lucaspickering.terraingen.util.Pair; import static org.lwjgl.system.MemoryStack.stackPush; public class TrueTypeFont { private static final int BITMAP_W = 512, BITMAP_H = 512; private static final int FIRST_CHAR = 32; private final Font font; private final STBTTBakedChar.Buffer charData; private int textureID; public TrueTypeFont(Font font) throws IOException, FontFormatException { this.font = font; this.charData = init(); } private STBTTBakedChar.Buffer init() { textureID = GL11.glGenTextures(); final STBTTBakedChar.Buffer cdata = STBTTBakedChar.malloc(96); try { final ByteBuffer ttf = Funcs.ioResourceToByteBuffer(Constants.FONT_PATH, font.getFontName(), 160 * 1024); final ByteBuffer bitmap = BufferUtils.createByteBuffer(BITMAP_W * BITMAP_H); STBTruetype.stbtt_BakeFontBitmap(ttf, getFontHeight(), bitmap, BITMAP_W, BITMAP_H, FIRST_CHAR, cdata); GL11.glBindTexture(GL11.GL_TEXTURE_2D, textureID); GL11.glTexImage2D(GL11.GL_TEXTURE_2D, 0, GL11.GL_ALPHA, BITMAP_W, BITMAP_H, 0, GL11.GL_ALPHA, GL11.GL_UNSIGNED_BYTE, bitmap); GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MAG_FILTER, GL11.GL_LINEAR); GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MIN_FILTER, GL11.GL_LINEAR); } catch (IOException e) { throw new RuntimeException(e); } return cdata; } private float getCharWidth(char c) { return 16; } private int getFontHeight() { return font.getFontHeight(); } private int getStringWidth(String s) { return (int) s.chars() .mapToDouble(c -> getCharWidth((char) c)) // Get the width of each character .sum(); // Sum up all the widths } /** * @see #getStringSize(String) */ private Pair<Integer, Integer> getStringSize(List<String> lines) { // Calculate width as the max of the width of each line final int width = lines.stream() .mapToInt(this::getStringWidth) // Get the width of each string .max() // Find max of each width .orElse(0); // Get the max or 0 if there is none // Calculate height as the sum of the height of each line final int height = getFontHeight() * lines.size(); return new Pair<>(width, height); } /** * Gets the size of the given string in pixels when drawn. The size is given as a * (width, height) pair. * * @param text the string to be drawn * @return the size of the string in (width, height) format */ public Pair<Integer, Integer> getStringSize(String text) { Objects.requireNonNull(text); return getStringSize(splitLines(text)); } private List<String> splitLines(String text) { return Arrays.asList(text.split("\n")); } private boolean isDrawable(char c) { // Range of drawable ASCII characters return FIRST_CHAR <= c && c <= 127; } private float shiftY(int y) { // Magic method for correcting y position of text. Not sure why this works. return y + getFontHeight() * 0.5f + 4f; } /** * Draw the given text in this font. * * @param text the text to draw (non-null) * @param x the x location to draw at * @param y the y location to draw at * @param color the color to draw with * @param horizAlign the {@link HorizAlignment} to draw with * @param vertAlign the {@link VertAlignment} to draw with * @throws NullPointerException if {@code text == null} */ public void draw(String text, int x, int y, Color color, HorizAlignment horizAlign, VertAlignment vertAlign) { Objects.requireNonNull(text); final List<String> lines = splitLines(text); final Pair<Integer, Integer> stringSize = getStringSize(lines); // Pair of (width, height) x += horizAlign.leftAdjustment(stringSize.first()); // Shift x for alignment y += vertAlign.topAdjustment(stringSize.second()); // Shift y for alignment // Bind this font's texture and set the color GL11.glBindTexture(GL11.GL_TEXTURE_2D, textureID); Funcs.setGlColor(color); // Draw the text try (MemoryStack stack = stackPush()) { final FloatBuffer xFloatBuffer = stack.floats(x); final FloatBuffer yFloatBuffer = stack.floats(shiftY(y)); final STBTTAlignedQuad quad = STBTTAlignedQuad.mallocStack(stack); GL11.glBegin(GL11.GL_QUADS); // Draw each line for (String line : lines) { // Draw each character in the line for (char c : line.toCharArray()) { // Skip invalid characters if (!isDrawable(c)) { continue; } STBTruetype.stbtt_GetBakedQuad(charData, BITMAP_W, BITMAP_H, c - FIRST_CHAR, xFloatBuffer, yFloatBuffer, quad, true); GL11.glTexCoord2f(quad.s0(), quad.t0()); GL11.glVertex2f(quad.x0(), quad.y0()); GL11.glTexCoord2f(quad.s1(), quad.t0()); GL11.glVertex2f(quad.x1(), quad.y0()); GL11.glTexCoord2f(quad.s1(), quad.t1()); GL11.glVertex2f(quad.x1(), quad.y1()); GL11.glTexCoord2f(quad.s0(), quad.t1()); GL11.glVertex2f(quad.x0(), quad.y1()); } // Keep the same x, increase y by the height of the font xFloatBuffer.put(0, x); yFloatBuffer.put(0, yFloatBuffer.get(0) + getFontHeight()); } GL11.glEnd(); } } public void delete() { charData.free(); } }
package net.atos.entng.forum.controllers; import java.util.Map; import net.atos.entng.forum.Forum; import net.atos.entng.forum.controllers.helpers.CategoryHelper; import net.atos.entng.forum.controllers.helpers.MessageHelper; import net.atos.entng.forum.controllers.helpers.SubjectHelper; import net.atos.entng.forum.filters.impl.ForumMessageMine; import net.atos.entng.forum.services.CategoryService; import net.atos.entng.forum.services.MessageService; import net.atos.entng.forum.services.SubjectService; import org.entcore.common.events.EventStore; import org.entcore.common.events.EventStoreFactory; import org.entcore.common.http.filter.ResourceFilter; import org.vertx.java.core.Vertx; import org.vertx.java.core.http.HttpServerRequest; import org.vertx.java.core.http.RouteMatcher; import org.vertx.java.platform.Container; import fr.wseduc.rs.ApiDoc; import fr.wseduc.rs.Delete; import fr.wseduc.rs.Get; import fr.wseduc.rs.Post; import fr.wseduc.rs.Put; import fr.wseduc.security.ActionType; import fr.wseduc.security.SecuredAction; import fr.wseduc.webutils.http.BaseController; public class ForumController extends BaseController { private final CategoryHelper categoryHelper; private final SubjectHelper subjectHelper; private final MessageHelper messageHelper; private EventStore eventStore; private enum ForumEvent { ACCESS } public ForumController(final String collection, final CategoryService categoryService, final SubjectService subjectService, final MessageService messageService) { this.categoryHelper = new CategoryHelper(collection, categoryService); this.subjectHelper = new SubjectHelper(subjectService, categoryService); this.messageHelper = new MessageHelper(messageService, subjectService); } @Override public void init(Vertx vertx, Container container, RouteMatcher rm, Map<String, fr.wseduc.webutils.security.SecuredAction> securedActions) { super.init(vertx, container, rm, securedActions); this.categoryHelper.init(vertx, container, rm, securedActions); this.subjectHelper.init(vertx, container, rm, securedActions); this.messageHelper.init(vertx, container, rm, securedActions); eventStore = EventStoreFactory.getFactory().getEventStore(Forum.class.getSimpleName()); } @Get("") @SecuredAction("forum.view") public void view(HttpServerRequest request) { renderView(request); // Create event "access to application Forum" and store it, for module "statistics" eventStore.createAndStoreEvent(ForumEvent.ACCESS.name(), request); } @Get("/categories") @SecuredAction("forum.list") public void listCategories(HttpServerRequest request) { categoryHelper.list(request); } @Post("/categories") @SecuredAction("forum.create") public void createCategory(HttpServerRequest request) { categoryHelper.create(request); } @Get("/category/:id") @SecuredAction(value = "category.read", type = ActionType.RESOURCE) public void getCategory(HttpServerRequest request) { categoryHelper.retrieve(request); } @Put("/category/:id") @SecuredAction(value = "category.manager", type = ActionType.RESOURCE) public void updateCategory(HttpServerRequest request) { categoryHelper.update(request); } @Delete("/category/:id") @SecuredAction(value = "category.manager", type = ActionType.RESOURCE) public void deleteCategory(HttpServerRequest request) { categoryHelper.delete(request); } @Get("/share/json/:id") @ApiDoc("Share thread by id.") @SecuredAction(value = "category.manager", type = ActionType.RESOURCE) public void shareCategory(final HttpServerRequest request) { categoryHelper.share(request); } @Put("/share/json/:id") @ApiDoc("Share thread by id.") @SecuredAction(value = "category.manager", type = ActionType.RESOURCE) public void shareCategorySubmit(final HttpServerRequest request) { categoryHelper.shareSubmit(request); } @Put("/share/remove/:id") @ApiDoc("Remove Share by id.") @SecuredAction(value = "category.manager", type = ActionType.RESOURCE) public void removeShareCategory(final HttpServerRequest request) { categoryHelper.shareRemove(request); } @Get("/category/:id/subjects") @SecuredAction(value = "category.read", type = ActionType.RESOURCE) public void listSubjects(HttpServerRequest request) { subjectHelper.list(request); } @Post("/category/:id/subjects") @SecuredAction(value = "category.publish", type = ActionType.RESOURCE) public void createSubject(HttpServerRequest request) { subjectHelper.create(request); } @Get("/category/:id/subject/:subjectid") @SecuredAction(value = "category.read", type = ActionType.RESOURCE) public void getSubject(HttpServerRequest request) { subjectHelper.retrieve(request); } @Put("/category/:id/subject/:subjectid") @SecuredAction(value = "category.publish", type = ActionType.RESOURCE) public void updateSubject(HttpServerRequest request) { subjectHelper.update(request); } @Delete("/category/:id/subject/:subjectid") @SecuredAction(value = "category.publish", type = ActionType.RESOURCE) public void deleteSubject(HttpServerRequest request) { subjectHelper.delete(request); } @Get("/category/:id/subject/:subjectid/messages") @SecuredAction(value = "category.read", type = ActionType.RESOURCE) public void listMessages(HttpServerRequest request) { messageHelper.list(request); } @Post("/category/:id/subject/:subjectid/messages") @SecuredAction(value = "category.contrib", type = ActionType.RESOURCE) public void createMessage(HttpServerRequest request) { messageHelper.create(request); } @Get("/category/:id/subject/:subjectid/message/:messageid") @SecuredAction(value = "category.read", type = ActionType.RESOURCE) public void getMessage(HttpServerRequest request) { messageHelper.retrieve(request); } @Put("/category/:id/subject/:subjectid/message/:messageid") @ResourceFilter(ForumMessageMine.class) @SecuredAction(value = "category.publish", type = ActionType.RESOURCE) public void updateMessage(HttpServerRequest request) { messageHelper.update(request); } @Delete("/category/:id/subject/:subjectid/message/:messageid") @SecuredAction(value = "category.publish", type = ActionType.RESOURCE) public void deleteMessage(HttpServerRequest request) { messageHelper.delete(request); } }
package org.antlr.intellij.plugin; import com.intellij.openapi.components.ProjectComponent; import com.intellij.openapi.project.Project; import com.intellij.openapi.project.ProjectManager; import com.intellij.openapi.roots.ProjectFileIndex; import com.intellij.openapi.roots.ProjectRootManager; import com.intellij.openapi.vfs.VirtualFile; import org.antlr.intellij.plugin.preview.ParseTreePanel; import org.antlr.v4.Tool; import org.antlr.v4.parse.ANTLRParser; import org.antlr.v4.runtime.ANTLRInputStream; import org.antlr.v4.runtime.CommonTokenStream; import org.antlr.v4.runtime.ConsoleErrorListener; import org.antlr.v4.runtime.LexerInterpreter; import org.antlr.v4.runtime.ParserInterpreter; import org.antlr.v4.runtime.RecognitionException; import org.antlr.v4.runtime.Recognizer; import org.antlr.v4.runtime.misc.Nullable; import org.antlr.v4.runtime.tree.ParseTree; import org.antlr.v4.tool.ANTLRMessage; import org.antlr.v4.tool.DefaultToolListener; import org.antlr.v4.tool.Grammar; import org.antlr.v4.tool.LexerGrammar; import org.antlr.v4.tool.ast.GrammarRootAST; import org.jetbrains.annotations.NotNull; import org.stringtemplate.v4.ST; import javax.swing.*; import java.io.IOException; public class ANTLRv4ProjectComponent implements ProjectComponent { public ParseTreePanel treePanel; public Project project; public ANTLRv4ProjectComponent(Project project) { this.project = project; } public static ANTLRv4ProjectComponent getInstance(Project project) { ANTLRv4ProjectComponent pc = project.getComponent(ANTLRv4ProjectComponent.class); return pc; } public static Project getProjectForFile(VirtualFile virtualFile) { Project[] openProjects = ProjectManager.getInstance().getOpenProjects(); Project project = null; for (int i = 0; i < openProjects.length; i++) { Project p = openProjects[i]; ProjectFileIndex fileIndex = ProjectRootManager.getInstance(p).getFileIndex(); if ( fileIndex.isInContent(virtualFile) ) { project = p; } } return project; } public ParseTreePanel getViewerPanel() { return treePanel; } @Override public void initComponent() { } @Override public void projectOpened() { treePanel = new ParseTreePanel(); } @Override public void projectClosed() { } @Override public void disposeComponent() { } @NotNull @Override public String getComponentName() { return "antlr.ProjectComponent"; } // private ToolWindow getToolWindow() // ToolWindowManager toolWindowManager = ToolWindowManager.getInstance(_project); // ToolWindow toolWindow = toolWindowManager.getToolWindow(ParseTreeWindowFactory.ID); // if ( toolWindow!=null ) { // return toolWindow; // else { // return toolWindowManager.registerToolWindow(ID_TOOL_WINDOW, // _viewerPanel, // ToolWindowAnchor.RIGHT); // private boolean isToolWindowRegistered() // return ToolWindowManager.getInstance(_project).getToolWindow(ID_TOOL_WINDOW) != null; public static Object[] parseText(ParseTreePanel parseTreePanel, String inputText, String grammarFileName, String startRule) throws IOException { Tool antlr = new Tool(); antlr.errMgr = new PluginIgnoreMissingTokensFileErrorManager(antlr); antlr.errMgr.setFormat("antlr"); MyANTLRToolListener listener = new MyANTLRToolListener(antlr); antlr.addListener(listener); String combinedGrammarFileName = null; String lexerGrammarFileName = null; String parserGrammarFileName = null; Grammar g = antlr.loadGrammar(grammarFileName); // load to examine it // examine's Grammar AST from v4 itself; // hence use ANTLRParser.X not ANTLRv4Parser from this plugin switch ( g.getType() ) { case ANTLRParser.PARSER : parserGrammarFileName = grammarFileName; int i = grammarFileName.indexOf("Parser"); lexerGrammarFileName = grammarFileName.substring(0,i)+"Lexer.g4"; break; case ANTLRParser.LEXER : lexerGrammarFileName = grammarFileName; int i2 = grammarFileName.indexOf("Lexer"); parserGrammarFileName = grammarFileName.substring(0,i2)+"Parser.g4"; break; case ANTLRParser.COMBINED : combinedGrammarFileName = grammarFileName; break; } ANTLRInputStream input = new ANTLRInputStream(inputText); LexerInterpreter lexEngine; if ( combinedGrammarFileName!=null ) { // already loaded above if ( listener.grammarErrorMessage!=null ) { return null; } lexEngine = g.createLexerInterpreter(input); } else { LexerGrammar lg = null; try { lg = (LexerGrammar)Grammar.load(lexerGrammarFileName); } catch (ClassCastException cce) { System.err.println("File "+lexerGrammarFileName+" isn't a lexer grammar"); } if ( listener.grammarErrorMessage!=null ) { return null; } g = loadGrammar(antlr, parserGrammarFileName, lg); lexEngine = lg.createLexerInterpreter(input); } final JTextArea console = parseTreePanel.getConsole(); final MyConsoleErrorListener syntaxErrorListener = new MyConsoleErrorListener(); Object[] result = new Object[2]; CommonTokenStream tokens = new CommonTokenStream(lexEngine); ParserInterpreter parser = g.createParserInterpreter(tokens); parser.removeErrorListeners(); parser.addErrorListener(syntaxErrorListener); ParseTree t = parser.parse(g.getRule(startRule).index); console.setText(syntaxErrorListener.syntaxError); if ( t!=null ) { return new Object[] {parser, t}; } return null; } /** Same as loadGrammar(fileName) except import vocab from existing lexer */ public static Grammar loadGrammar(Tool tool, String fileName, LexerGrammar lexerGrammar) { GrammarRootAST grammarRootAST = tool.parseGrammar(fileName); final Grammar g = tool.createGrammar(grammarRootAST); g.fileName = fileName; g.importVocab(lexerGrammar); tool.process(g, false); return g; } static class MyANTLRToolListener extends DefaultToolListener { public String grammarErrorMessage; public MyANTLRToolListener(Tool tool) { super(tool); } @Override public void error(ANTLRMessage msg) { // super.error(msg); ST msgST = tool.errMgr.getMessageTemplate(msg); grammarErrorMessage = msgST.render(); if (tool.errMgr.formatWantsSingleLineMessage()) { grammarErrorMessage = grammarErrorMessage.replace('\n', ' '); } } } /** Traps parser interpreter syntax errors */ static class MyConsoleErrorListener extends ConsoleErrorListener { public String syntaxError=""; @Override public void syntaxError(Recognizer<?, ?> recognizer, @Nullable Object offendingSymbol, int line, int charPositionInLine, String msg, @Nullable RecognitionException e) { // super.syntaxError(recognizer, offendingSymbol, line, charPositionInLine, msg, e); syntaxError = "line " + line + ":" + charPositionInLine + " " + msg; } } }
package net.coobird.thumbnailator.tasks.io; import java.awt.image.BufferedImage; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.util.Iterator; import java.util.List; import java.util.NoSuchElementException; import javax.imageio.IIOImage; import javax.imageio.ImageIO; import javax.imageio.ImageReader; import javax.imageio.ImageWriteParam; import javax.imageio.ImageWriter; import javax.imageio.stream.ImageOutputStream; import net.coobird.thumbnailator.ThumbnailParameter; import net.coobird.thumbnailator.tasks.UnsupportedFormatException; import net.coobird.thumbnailator.util.BufferedImages; import net.coobird.thumbnailator.util.ThumbnailatorUtils; /** * An {@link ImageSink} which writes the resulting thumbnail to a file. * <p> * Under certain circumstances, the destination file can change in the course * of processing. * <p> * This can occur in cases where the file extension does not * match the output format set by the {@link #setOutputFormatName(String)} * method. In this case, the file name will have a file extension corresponding * to the output format set in the above method to be appended to the file * name originally provided when instantiating the {@link FileImageSink} object. * * @author coobird * */ public class FileImageSink implements ImageSink<File> { /** * The file to which the thumbnail is written to. * <p> * Under certain circumstances, the {@link File} object can be replaced * in the course of processing. This can occur in cases where the file * extension has been changed due to incongruence between the extension * and the desired output format. */ private File destinationFile; private final boolean allowOverwrite; private String outputFormat; private ThumbnailParameter param; /** * An {@link ImageSink} which actually performs the image writing * operations. This {@link ImageSink} can change during the lifecycle * of the {@link FileImageSink} class. */ private ImageSink<?> imageSink = new UninitializedImageSink(); /** * Temporary placeholder {@link ImageSink} which will be used before * the {@link #read()} method is used. Basically a way to use the * implementation of the {@link AbstractImageSink} without having to * instantiate a {@link OutputStreamImageSink} object before needed. */ private static class UninitializedImageSink extends AbstractImageSink<Void> { public Void getSink() { throw new IllegalStateException("This should not happen."); } } /** * Instantiates a {@link FileImageSink} with the file to which the thumbnail * should be written to. * <p> * The output format to use will be determined from the file extension. * If another format should be used, then the * {@link #setOutputFormatName(String)} should be called with the desired * output format name. * <p> * When the destination file exists, then this {@code FileImageSink} will * overwrite the existing file. * * @param destinationFile The destination file. * @throws NullPointerException If the specified file is {@code null}. */ public FileImageSink(File destinationFile) { this(destinationFile, true); } /** * Instantiates a {@link FileImageSink} with the file to which the thumbnail * should be written to. * <p> * The output format to use will be determined from the file extension. * If another format should be used, then the * {@link #setOutputFormatName(String)} should be called with the desired * output format name. * * @param destinationFile The destination file. * @param allowOverwrite Whether or not the {@code FileImageSink} * should overwrite the destination file if * it already exists. * @throws NullPointerException If the specified file is {@code null}. */ public FileImageSink(File destinationFile, boolean allowOverwrite) { super(); if (destinationFile == null) { throw new NullPointerException("File cannot be null."); } this.destinationFile = destinationFile; this.outputFormat = getExtension(destinationFile); this.allowOverwrite = allowOverwrite; } /** * Instantiates a {@link FileImageSink} with the file to which the thumbnail * should be written to. * <p> * The output format to use will be determined from the file extension. * If another format should be used, then the * {@link #setOutputFormatName(String)} should be called with the desired * output format name. * <p> * When the destination file exists, then this {@code FileImageSink} will * overwrite the existing file. * * @param destinationFilePath The destination file path. * @throws NullPointerException If the specified file path is {@code null}. */ public FileImageSink(String destinationFilePath) { this(destinationFilePath, true); } /** * Instantiates a {@link FileImageSink} with the file to which the thumbnail * should be written to. * <p> * The output format to use will be determined from the file extension. * If another format should be used, then the * {@link #setOutputFormatName(String)} should be called with the desired * output format name. * * @param destinationFilePath The destination file path. * @param allowOverwrite Whether or not the {@code FileImageSink} * should overwrite the destination file if * it already exists. * @throws NullPointerException If the specified file path is {@code null}. */ public FileImageSink(String destinationFilePath, boolean allowOverwrite) { super(); if (destinationFilePath == null) { throw new NullPointerException("File cannot be null."); } this.destinationFile = new File(destinationFilePath); this.outputFormat = getExtension(destinationFile); this.allowOverwrite = allowOverwrite; } /** * Determines whether an specified format name and file extension are * for the same format. * * @param formatName Format name. * @param fileExtension File extension. * @return Returns {@code true} if the specified file * extension is valid for the specified format. */ private static boolean isMatchingFormat(String formatName, String fileExtension) throws UnsupportedFormatException { if (formatName == null || fileExtension == null) { return false; } ImageWriter iw; try { iw = ImageIO.getImageWritersByFormatName(formatName).next(); } catch (NoSuchElementException e) { throw new UnsupportedFormatException( formatName, "No suitable ImageWriter found for " + formatName + "." ); } String[] suffixes = iw.getOriginatingProvider().getFileSuffixes(); for (String suffix : suffixes) { if (fileExtension.equalsIgnoreCase(suffix)) { return true; } } return false; } /** * Returns the file extension of the given {@link File}. * * @param f The file. * @return The extension of the file. */ private static String getExtension(File f) { String fileName = f.getName(); if ( fileName.indexOf('.') != -1 && fileName.lastIndexOf('.') != fileName.length() - 1 ) { int lastIndex = fileName.lastIndexOf('.'); return fileName.substring(lastIndex + 1); } return null; } public String preferredOutputFormatName() { String fileExtension = getExtension(destinationFile); if (fileExtension != null) { Iterator<ImageReader> rIter = ImageIO.getImageReadersBySuffix(fileExtension); if (rIter.hasNext()) { try { return rIter.next().getFormatName(); } catch (IOException e) { return ThumbnailParameter.ORIGINAL_FORMAT; } } } return outputFormat; } public void write(BufferedImage img) throws IOException { /* * Add or replace the file extension of the output file. * * If the file extension matches the output format's extension, * then leave as is. * * Else, append the extension for the output format to the filename. */ String fileExtension = getExtension(destinationFile); String formatName = outputFormat; if (formatName != null && (fileExtension == null || !isMatchingFormat(formatName, fileExtension))) { destinationFile = new File(destinationFile.getAbsolutePath() + "." + formatName); } if (!allowOverwrite && destinationFile.exists()) { throw new IllegalArgumentException("The destination file exists."); } /* * If a formatName is not specified, then attempt to determine it from * the file extension. */ if (formatName == null && fileExtension != null) { Iterator<ImageReader> rIter = ImageIO.getImageReadersBySuffix(fileExtension); if (rIter.hasNext()) { formatName = rIter.next().getFormatName(); } } if (formatName == null) { throw new UnsupportedFormatException( formatName, "Could not determine output format." ); } imageSink = new OutputStreamImageSink(new FileOutputStream(destinationFile)); imageSink.setThumbnailParameter(param); imageSink.setOutputFormatName(formatName); imageSink.write(img); } /** * Returns the detination file of the thumbnail image. * <p> * If the final destination of the thumbnail changes in the course of * writing the thumbnail. (For example, if the file extension for the given * destination did not match the destination file format, then the correct * file extension could be appended.) * * @return the destinationFile */ public File getSink() { return destinationFile; } public void setOutputFormatName(String format) { this.outputFormat = format; this.imageSink.setOutputFormatName(format); } public void setThumbnailParameter(ThumbnailParameter param) { this.param = param; this.imageSink.setThumbnailParameter(param); } }
package org.apache.commons.jxpath.util; import java.lang.reflect.Array; import java.lang.reflect.Modifier; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Set; import org.apache.commons.jxpath.JXPathException; import org.apache.commons.jxpath.Pointer; import org.apache.commons.jxpath.NodeSet; public class BasicTypeConverter implements TypeConverter { /** * Returns true if it can convert the supplied * object to the specified class. */ public boolean canConvert(Object object, Class toType) { if (object == null) { return true; } if (toType == Object.class) { return true; } Class fromType = object.getClass(); if (fromType.equals(toType)) { return true; } if (toType.isAssignableFrom(fromType)) { return true; } if (toType == String.class) { return true; } if (object instanceof Boolean) { if (toType == boolean.class || Number.class.isAssignableFrom(toType)) { return true; } } else if (object instanceof Number) { if (toType.isPrimitive() || Number.class.isAssignableFrom(toType)) { return true; } } else if (object instanceof Character) { if (toType == char.class) { return true; } } else if (object instanceof String) { if (toType.isPrimitive()) { return true; } if (toType == Boolean.class || toType == Character.class || toType == Byte.class || toType == Short.class || toType == Integer.class || toType == Long.class || toType == Float.class || toType == Double.class) { return true; } } else if (fromType.isArray()) { // Collection -> array if (toType.isArray()) { Class cType = toType.getComponentType(); int length = Array.getLength(object); for (int i = 0; i < length; i++) { Object value = Array.get(object, i); if (!canConvert(value, cType)) { return false; } } return true; } else if (Collection.class.isAssignableFrom(toType)) { return canCreateCollection(toType); } else { if (Array.getLength(object) > 0) { Object value = Array.get(object, 0); return canConvert(value, toType); } else { return canConvert("", toType); } } } else if (object instanceof Collection) { // Collection -> array if (toType.isArray()) { Class cType = toType.getComponentType(); Iterator it = ((Collection) object).iterator(); while (it.hasNext()) { Object value = it.next(); if (!canConvert(value, cType)) { return false; } } return true; } else if (Collection.class.isAssignableFrom(toType)) { return canCreateCollection(toType); } else { if (((Collection) object).size() > 0) { Object value; if (object instanceof List) { value = ((List) object).get(0); } else { Iterator it = ((Collection) object).iterator(); value = it.next(); } return canConvert(value, toType); } else { return canConvert("", toType); } } } else if (object instanceof NodeSet) { return canConvert(((NodeSet) object).getValues(), toType); } else if (object instanceof Pointer) { return canConvert(((Pointer) object).getValue(), toType); } return false; } /** * Converts the supplied object to the specified * type. Throws a runtime exception if the conversion is * not possible. */ public Object convert(Object object, Class toType) { if (object == null) { if (toType.isPrimitive()) { return convertNullToPrimitive(toType); } return null; } if (toType == Object.class) { return object; } Class fromType = object.getClass(); if (fromType.equals(toType) || toType.isAssignableFrom(fromType)) { return object; } if (fromType.isArray()) { int length = Array.getLength(object); if (toType.isArray()) { Class cType = toType.getComponentType(); Object array = Array.newInstance(cType, length); for (int i = 0; i < length; i++) { Object value = Array.get(object, i); Array.set(array, i, convert(value, cType)); } return array; } else if (Collection.class.isAssignableFrom(toType)) { Collection collection = allocateCollection(toType); for (int i = 0; i < length; i++) { collection.add(Array.get(object, i)); } return unmodifiableCollection(collection); } else { if (length > 0) { Object value = Array.get(object, 0); return convert(value, toType); } else { return convert("", toType); } } } else if (object instanceof Collection) { int length = ((Collection) object).size(); if (toType.isArray()) { Class cType = toType.getComponentType(); Object array = Array.newInstance(cType, length); Iterator it = ((Collection) object).iterator(); for (int i = 0; i < length; i++) { Object value = it.next(); Array.set(array, i, convert(value, cType)); } return array; } else if (Collection.class.isAssignableFrom(toType)) { Collection collection = allocateCollection(toType); collection.addAll((Collection) object); return unmodifiableCollection(collection); } else { if (length > 0) { Object value; if (object instanceof List) { value = ((List) object).get(0); } else { Iterator it = ((Collection) object).iterator(); value = it.next(); } return convert(value, toType); } else { return convert("", toType); } } } else if (object instanceof NodeSet) { return convert(((NodeSet) object).getValues(), toType); } else if (object instanceof Pointer) { return convert(((Pointer) object).getValue(), toType); } else if (toType == String.class) { return object.toString(); } else if (object instanceof Boolean) { if (toType == boolean.class) { return object; } boolean value = ((Boolean) object).booleanValue(); return allocateNumber(toType, value ? 1 : 0); } else if (object instanceof Number) { double value = ((Number) object).doubleValue(); if (toType == boolean.class || toType == Boolean.class) { return value == 0.0 ? Boolean.FALSE : Boolean.TRUE; } if (toType.isPrimitive() || Number.class.isAssignableFrom(toType)) { return allocateNumber(toType, value); } } else if (object instanceof Character) { if (toType == char.class) { return object; } } else if (object instanceof String) { Object value = convertStringToPrimitive(object, toType); if (value != null) { return value; } } throw new RuntimeException( "Cannot convert " + object.getClass() + " to " + toType); } protected Object convertNullToPrimitive(Class toType) { if (toType == boolean.class) { return Boolean.FALSE; } if (toType == char.class) { return new Character('\0'); } if (toType == byte.class) { return new Byte((byte) 0); } if (toType == short.class) { return new Short((short) 0); } if (toType == int.class) { return new Integer(0); } if (toType == long.class) { return new Long(0L); } if (toType == float.class) { return new Float(0.0f); } if (toType == double.class) { return new Double(0.0); } return null; } protected Object convertStringToPrimitive(Object object, Class toType) { if (toType == boolean.class || toType == Boolean.class) { return Boolean.valueOf((String) object); } if (toType == char.class || toType == Character.class) { return new Character(((String) object).charAt(0)); } if (toType == byte.class || toType == Byte.class) { return new Byte((String) object); } if (toType == short.class || toType == Short.class) { return new Short((String) object); } if (toType == int.class || toType == Integer.class) { return new Integer((String) object); } if (toType == long.class || toType == Long.class) { return new Long((String) object); } if (toType == float.class || toType == Float.class) { return new Float((String) object); } if (toType == double.class || toType == Double.class) { return new Double((String) object); } return null; } protected Number allocateNumber(Class type, double value) { if (type == Byte.class || type == byte.class) { return new Byte((byte) value); } if (type == Short.class || type == short.class) { return new Short((short) value); } if (type == Integer.class || type == int.class) { return new Integer((int) value); } if (type == Long.class || type == long.class) { return new Long((long) value); } if (type == Float.class || type == float.class) { return new Float((float) value); } if (type == Double.class || type == double.class) { return new Double(value); } return null; } protected boolean canCreateCollection(Class type) { if (!type.isInterface() && ((type.getModifiers() | Modifier.ABSTRACT) == 0)) { return true; } if (type == List.class) { return true; } if (type == Set.class) { return true; } return false; } protected Collection allocateCollection(Class type) { if (!type.isInterface() && ((type.getModifiers() | Modifier.ABSTRACT) == 0)) { try { return (Collection) type.newInstance(); } catch (Exception ex) { throw new JXPathException( "Cannot create collection of type: " + type, ex); } } if (type == List.class) { return new ArrayList(); } if (type == Set.class) { return new HashSet(); } throw new RuntimeException("Cannot create collection of type: " + type); } protected Collection unmodifiableCollection(Collection collection) { if (collection instanceof List) { return Collections.unmodifiableList((List) collection); } else if (collection instanceof Set) { return Collections.unmodifiableSet((Set) collection); } // Cannot wrap it into a proper unmodifiable collection, // so we just return the original collection itself return collection; } static final class ValueNodeSet implements NodeSet { private List values; private List pointers; public ValueNodeSet(List values) { this.values = values; } public List getValues() { return Collections.unmodifiableList(values); } public List getNodes() { return Collections.unmodifiableList(values); } public List getPointers() { if (pointers == null) { pointers = new ArrayList(); for (int i = 0; i < values.size(); i++) { pointers.add(new ValuePointer(values.get(i))); } pointers = Collections.unmodifiableList(pointers); } return pointers; } } static final class ValuePointer implements Pointer { private Object bean; public ValuePointer(Object object) { this.bean = object; } public Object getValue() { return bean; } public Object getNode() { return bean; } public Object getRootNode() { return bean; } public void setValue(Object value) { throw new UnsupportedOperationException(); } public Object clone() { return this; } public int compareTo(Object object) { return 0; } public String asPath() { if (bean == null) { return "null()"; } else if (bean instanceof Number) { String string = bean.toString(); if (string.endsWith(".0")) { string = string.substring(0, string.length() - 2); } return string; } else if (bean instanceof Boolean) { return ((Boolean) bean).booleanValue() ? "true()" : "false()"; } else if (bean instanceof String) { return "'" + bean + "'"; } return "{object of type " + bean.getClass().getName() + "}"; } } }
package com.yahoo.squidb.data; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteException; import com.yahoo.squidb.data.adapter.SQLiteDatabaseWrapper; import com.yahoo.squidb.sql.Field; import com.yahoo.squidb.sql.Property; import com.yahoo.squidb.sql.Property.StringProperty; import com.yahoo.squidb.sql.Query; import com.yahoo.squidb.sql.TableStatement; import com.yahoo.squidb.test.DatabaseTestCase; import com.yahoo.squidb.test.Employee; import com.yahoo.squidb.test.SquidTestRunner; import com.yahoo.squidb.test.SquidTestRunner.SquidbBinding; import com.yahoo.squidb.test.TestDatabase; import com.yahoo.squidb.test.TestModel; import com.yahoo.squidb.test.TestViewModel; import com.yahoo.squidb.test.Thing; import com.yahoo.squidb.utility.VersionCode; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Random; import java.util.concurrent.Semaphore; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicReference; public class SquidDatabaseTest extends DatabaseTestCase { private BadDatabase badDatabase; @Override protected void setupDatabase() { super.setupDatabase(); badDatabase = new BadDatabase(getContext()); badDatabase.getDatabase(); // init } @Override protected void tearDownDatabase() { super.tearDownDatabase(); badDatabase.clear(); } public void testRawQuery() { badDatabase.persist(new TestModel().setFirstName("Sam").setLastName("Bosley").setBirthday(testDate)); Cursor cursor = null; try { // Sanity check that there is only one row in the table assertEquals(1, badDatabase.countAll(TestModel.class)); // Test that raw query binds arguments correctly--if the argument // is bound as a String, the result will be empty cursor = badDatabase.rawQuery("select * from testModels where abs(_id) = ?", new Object[]{1}); assertEquals(1, cursor.getCount()); } finally { if (cursor != null) { cursor.close(); } } } public void testTryAddColumn() { StringProperty goodProperty = new StringProperty(TestModel.TABLE, "good_column"); badDatabase.tryAddColumn(goodProperty); // don't care about the result, just that it didn't throw final StringProperty badProperty = new StringProperty(TestViewModel.VIEW, "bad_column"); testThrowsException(new Runnable() { @Override public void run() { badDatabase.tryAddColumn(badProperty); } }, IllegalArgumentException.class); } public void testMigrationFailureCalledWhenOnUpgradeReturnsFalse() { testMigrationFailureCalled(true, false, false, false); } public void testMigrationFailureCalledWhenOnUpgradeThrowsException() { testMigrationFailureCalled(true, true, false, false); } public void testMigrationFailureCalledWhenOnDowngradeReturnsFalse() { testMigrationFailureCalled(false, false, false, false); } public void testMigrationFailureCalledWhenOnDowngradeThrowsException() { testMigrationFailureCalled(false, true, false, false); } private void testMigrationFailureCalled(boolean upgrade, boolean shouldThrow, boolean shouldRecreateDuringMigration, boolean shouldRecreateOnMigrationFailed) { badDatabase.setShouldThrowDuringMigration(shouldThrow); badDatabase.setShouldRecreateInMigration(shouldRecreateDuringMigration); badDatabase.setShouldRecreateInOnMigrationFailed(shouldRecreateOnMigrationFailed); // set version manually SQLiteDatabaseWrapper db = badDatabase.getDatabase(); final int version = db.getVersion(); final int previousVersion = upgrade ? version - 1 : version + 1; db.setVersion(previousVersion); // close and reopen to trigger an upgrade/downgrade badDatabase.onTablesCreatedCalled = false; badDatabase.close(); badDatabase.getDatabase(); assertTrue(upgrade ? badDatabase.onUpgradeCalled : badDatabase.onDowngradeCalled); if (shouldRecreateDuringMigration || shouldRecreateOnMigrationFailed) { assertTrue(badDatabase.onTablesCreatedCalled); } else { assertTrue(badDatabase.onMigrationFailedCalled); assertEquals(previousVersion, badDatabase.migrationFailedOldVersion); assertEquals(version, badDatabase.migrationFailedNewVersion); } } /** * {@link SquidDatabase} does not automatically recreate the database when a migration fails. This is really to * test that {@link SquidDatabase#recreate()} can safely be called during onUpgrade or * onDowngrade as an exemplar for client developers. */ public void testRecreateOnUpgradeFailure() { testRecreateDuringMigrationOrFailureCallback(true, false); } public void testRecreateOnDowngradeFailure() { testRecreateDuringMigrationOrFailureCallback(false, false); } public void testRecreateDuringOnMigrationFailed() { testRecreateDuringMigrationOrFailureCallback(true, true); } private void testRecreateDuringMigrationOrFailureCallback(boolean upgrade, boolean recreateDuringMigration) { // insert some data to check for later badDatabase.persist(new Employee().setName("Alice")); badDatabase.persist(new Employee().setName("Bob")); badDatabase.persist(new Employee().setName("Cindy")); assertEquals(3, badDatabase.countAll(Employee.class)); testMigrationFailureCalled(upgrade, recreateDuringMigration, true, recreateDuringMigration); // verify the db was recreated with the appropriate version and no previous data SQLiteDatabaseWrapper db = badDatabase.getDatabase(); assertEquals(badDatabase.getVersion(), db.getVersion()); assertEquals(0, badDatabase.countAll(Employee.class)); } public void testExceptionDuringOpenCleansUp() { badDatabase.setShouldThrowDuringMigration(true); badDatabase.setShouldRecreateInMigration(false); badDatabase.setShouldRecreateInOnMigrationFailed(false); badDatabase.setShouldRethrowInOnMigrationFailed(true); testThrowsException(new Runnable() { @Override public void run() { // set version manually SQLiteDatabaseWrapper db = badDatabase.getDatabase(); final int version = db.getVersion(); final int previousVersion = version - 1; db.setVersion(previousVersion); // close and reopen to trigger an upgrade/downgrade badDatabase.onTablesCreatedCalled = false; badDatabase.close(); badDatabase.getDatabase(); } }, SquidDatabase.MigrationFailedException.class); assertFalse(badDatabase.inTransaction()); assertFalse(badDatabase.isOpen()); } public void testAcquireExclusiveLockFailsWhenInTransaction() { testThrowsException(new Runnable() { @Override public void run() { IllegalStateException caughtException = null; badDatabase.beginTransaction(); try { badDatabase.acquireExclusiveLock(); } catch (IllegalStateException e) { // Need to do this in the catch block rather than the finally block, because otherwise tearDown is // called before we have a chance to release the transaction lock badDatabase.endTransaction(); caughtException = e; } finally { if (caughtException == null) { // Sanity cleanup if catch block was never reached badDatabase.endTransaction(); } } if (caughtException != null) { throw caughtException; } } }, IllegalStateException.class); } public void testCustomMigrationException() { TestDatabase database = new TestDatabase(getContext()); SQLiteDatabaseWrapper db = database.getDatabase(); // force a downgrade final int version = db.getVersion(); final int previousVersion = version + 1; db.setVersion(previousVersion); database.close(); database.getDatabase(); try { assertTrue(database.caughtCustomMigrationException); } finally { database.clear(); // clean up since this is the only test using it } } /** * {@link TestDatabase} that intentionally fails in onUpgrade and onDowngrade */ private static class BadDatabase extends TestDatabase { private boolean onMigrationFailedCalled = false; private boolean onUpgradeCalled = false; private boolean onDowngradeCalled = false; private boolean onTablesCreatedCalled = false; private int migrationFailedOldVersion = 0; private int migrationFailedNewVersion = 0; private boolean shouldThrowDuringMigration = false; private boolean shouldRecreateInMigration = false; private boolean shouldRecreateInOnMigrationFailed = false; private boolean shouldRethrowInOnMigrationFailed = false; public BadDatabase(Context context) { super(context); } @Override public String getName() { return "badDb"; } @Override protected int getVersion() { return super.getVersion() + 1; } @Override protected void onTablesCreated(SQLiteDatabaseWrapper db) { onTablesCreatedCalled = true; } @Override protected final boolean onUpgrade(SQLiteDatabaseWrapper db, int oldVersion, int newVersion) { onUpgradeCalled = true; if (shouldThrowDuringMigration) { throw new SQLiteException("My name is \"NO! NO! BAD DATABASE!\". What's yours?"); } else if (shouldRecreateInMigration) { recreate(); } return false; } @Override protected boolean onDowngrade(SQLiteDatabaseWrapper db, int oldVersion, int newVersion) { onDowngradeCalled = true; if (shouldThrowDuringMigration) { throw new SQLiteException("My name is \"NO! NO! BAD DATABASE!\". What's yours?"); } else if (shouldRecreateInMigration) { recreate(); } return false; } @Override protected void onMigrationFailed(MigrationFailedException failure) { onMigrationFailedCalled = true; migrationFailedOldVersion = failure.oldVersion; migrationFailedNewVersion = failure.newVersion; if (shouldRecreateInOnMigrationFailed) { recreate(); } else if (shouldRethrowInOnMigrationFailed) { throw failure; } } public void setShouldThrowDuringMigration(boolean flag) { shouldThrowDuringMigration = flag; } public void setShouldRecreateInMigration(boolean flag) { shouldRecreateInMigration = flag; } public void setShouldRecreateInOnMigrationFailed(boolean flag) { shouldRecreateInOnMigrationFailed = flag; } public void setShouldRethrowInOnMigrationFailed(boolean flag) { shouldRethrowInOnMigrationFailed = flag; } @Override protected boolean tryAddColumn(Property<?> property) { return super.tryAddColumn(property); } } public void testBasicInsertAndFetch() { TestModel model = insertBasicTestModel(); TestModel fetch = database.fetch(TestModel.class, model.getId(), TestModel.PROPERTIES); assertEquals("Sam", fetch.getFirstName()); assertEquals("Bosley", fetch.getLastName()); assertEquals(testDate, fetch.getBirthday().longValue()); } public void testPropertiesAreNullable() { TestModel model = insertBasicTestModel(); model.setFirstName(null); model.setLastName(null); assertNull(model.getFirstName()); assertNull(model.getLastName()); database.persist(model); TestModel fetch = database.fetch(TestModel.class, model.getId(), TestModel.PROPERTIES); assertNull(fetch.getFirstName()); assertNull(fetch.getLastName()); } public void testBooleanProperties() { TestModel model = insertBasicTestModel(); assertTrue(model.isHappy()); model.setIsHappy(false); assertFalse(model.isHappy()); database.persist(model); TestModel fetch = database.fetch(TestModel.class, model.getId(), TestModel.PROPERTIES); assertFalse(fetch.isHappy()); } public void testQueriesWithBooleanPropertiesWork() { insertBasicTestModel(); SquidCursor<TestModel> result = database.query(TestModel.class, Query.select(TestModel.PROPERTIES).where(TestModel.IS_HAPPY.isTrue())); assertEquals(1, result.getCount()); result.moveToFirst(); TestModel model = new TestModel(result); assertTrue(model.isHappy()); model.setIsHappy(false); database.persist(model); result.close(); result = database.query(TestModel.class, Query.select(TestModel.PROPERTIES).where(TestModel.IS_HAPPY.isFalse())); assertEquals(1, result.getCount()); result.moveToFirst(); model = new TestModel(result); assertFalse(model.isHappy()); } public void testConflict() { insertBasicTestModel(); TestModel conflict = new TestModel(); conflict.setFirstName("Dave"); conflict.setLastName("Bosley"); boolean result = database.persistWithOnConflict(conflict, TableStatement.ConflictAlgorithm.IGNORE); assertFalse(result); TestModel shouldntExist = database.fetchByCriterion(TestModel.class, TestModel.FIRST_NAME.eq("Dave").and(TestModel.LAST_NAME.eq("Bosley")), TestModel.PROPERTIES); assertNull(shouldntExist); RuntimeException expected = null; try { conflict.clearValue(TestModel.ID); database.persistWithOnConflict(conflict, TableStatement.ConflictAlgorithm.FAIL); } catch (RuntimeException e) { expected = e; } assertNotNull(expected); } public void testListProperty() { TestModel model = insertBasicTestModel(); List<String> numbers = Arrays.asList("0", "1", "2", "3"); model.setSomeList(numbers); database.persist(model); model = database.fetch(TestModel.class, model.getId(), TestModel.PROPERTIES); List<String> readNumbers = model.getSomeList(); assertEquals(numbers.size(), readNumbers.size()); for (int i = 0; i < numbers.size(); i++) { assertEquals(numbers.get(i), readNumbers.get(i)); } } public void testFetchByQueryResetsLimitAndTable() { TestModel model1 = new TestModel().setFirstName("Sam1").setLastName("Bosley1"); TestModel model2 = new TestModel().setFirstName("Sam2").setLastName("Bosley2"); TestModel model3 = new TestModel().setFirstName("Sam3").setLastName("Bosley3"); database.persist(model1); database.persist(model2); database.persist(model3); Query query = Query.select().limit(2, 1); TestModel fetched = database.fetchByQuery(TestModel.class, query); assertEquals(model2.getId(), fetched.getId()); assertEquals(Field.field("2"), query.getLimit()); assertEquals(Field.field("1"), query.getOffset()); assertEquals(null, query.getTable()); } public void testEqCaseInsensitive() { insertBasicTestModel(); TestModel fetch = database.fetchByCriterion(TestModel.class, TestModel.LAST_NAME.eqCaseInsensitive("BOSLEY"), TestModel.PROPERTIES); assertNotNull(fetch); } public void testInsertRow() { TestModel model = insertBasicTestModel(); assertNotNull(database.fetch(TestModel.class, model.getId())); database.delete(TestModel.class, model.getId()); assertNull(database.fetch(TestModel.class, model.getId())); long modelId = model.getId(); database.insertRow(model); // Should reinsert the row with the same id assertEquals(modelId, model.getId()); assertNotNull(database.fetch(TestModel.class, model.getId())); assertEquals(1, database.countAll(TestModel.class)); } public void testVersionForCustomBinding() { if (SquidTestRunner.selectedBinding == SquidbBinding.SQLITE) { assertEquals(VersionCode.LATEST, database.getSqliteVersion()); } } public void testDropView() { database.tryDropView(TestViewModel.VIEW); testThrowsRuntimeException(new Runnable() { @Override public void run() { database.query(TestViewModel.class, Query.select().from(TestViewModel.VIEW)); } }); } public void testDropTable() { database.tryDropTable(TestModel.TABLE); testThrowsRuntimeException(new Runnable() { @Override public void run() { database.query(TestModel.class, Query.select().from(TestModel.TABLE)); } }); } public void testTryExecSqlReturnsFalseForInvalidSql() { assertFalse(database.tryExecSql("CREATE TABLE")); } public void testExecSqlOrThrowThrowsForInvalidSql() { testThrowsRuntimeException(new Runnable() { @Override public void run() { database.execSqlOrThrow("CREATE TABLE"); } }); testThrowsRuntimeException(new Runnable() { @Override public void run() { database.execSqlOrThrow("CREATE TABLE", null); } }); } public void testUpdateAll() { database.persist(new TestModel().setFirstName("A").setLastName("A") .setBirthday(System.currentTimeMillis() - 1).setLuckyNumber(1)); database.persist(new TestModel().setFirstName("A").setLastName("B") .setBirthday(System.currentTimeMillis() - 1).setLuckyNumber(2)); database.updateAll(new TestModel().setLuckyNumber(5)); assertEquals(0, database.count(TestModel.class, TestModel.LUCKY_NUMBER.neq(5))); } public void testDeleteAll() { insertBasicTestModel("A", "B", System.currentTimeMillis() - 1); insertBasicTestModel("C", "D", System.currentTimeMillis()); assertEquals(2, database.countAll(TestModel.class)); database.deleteAll(TestModel.class); assertEquals(0, database.countAll(TestModel.class)); } public void testConcurrentReadsWithWAL() { // Tests that concurrent reads can happen when using WAL, but only committed changes will be visible // on other threads insertBasicTestModel(); final Semaphore sema1 = new Semaphore(0); final Semaphore sema2 = new Semaphore(0); final AtomicInteger countBeforeCommit = new AtomicInteger(); final AtomicInteger countAfterCommit = new AtomicInteger(); Thread thread = new Thread(new Runnable() { @Override public void run() { try { sema2.acquire(); } catch (InterruptedException e) { fail(e.getMessage()); } countBeforeCommit.set(database.countAll(TestModel.class)); sema1.release(); try { sema2.acquire(); } catch (InterruptedException e) { fail(e.getMessage()); } countAfterCommit.set(database.countAll(TestModel.class)); } }); database.beginTransactionNonExclusive(); try { thread.start(); insertBasicTestModel("A", "B", System.currentTimeMillis() + 100); sema2.release(); try { sema1.acquire(); } catch (InterruptedException e) { fail(e.getMessage()); } database.setTransactionSuccessful(); } finally { database.endTransaction(); sema2.release(); } try { thread.join(); } catch (InterruptedException e) { fail(e.getMessage()); } assertEquals(1, countBeforeCommit.get()); assertEquals(2, countAfterCommit.get()); } public void testConcurrencyStressTest() { int numThreads = 20; final AtomicReference<Exception> exception = new AtomicReference<Exception>(); List<Thread> workers = new ArrayList<Thread>(); for (int i = 0; i < numThreads; i++) { Thread t = new Thread(new Runnable() { @Override public void run() { concurrencyStressTest(exception); } }); t.start(); workers.add(t); } for (Thread t : workers) { try { t.join(); } catch (Exception e) { exception.set(e); } } assertNull(exception.get()); } private void concurrencyStressTest(AtomicReference<Exception> exception) { try { Random r = new Random(); int numOperations = 100; Thing t = new Thing(); for (int i = 0; i < numOperations; i++) { int rand = r.nextInt(10); if (rand == 0) { database.close(); } else if (rand == 1) { database.clear(); } else if (rand == 2) { database.recreate(); } else if (rand == 3) { database.beginTransactionNonExclusive(); try { for (int j = 0; j < 20; j++) { t.setFoo(Integer.toString(j)) .setBar(-j); database.createNew(t); } database.setTransactionSuccessful(); } finally { database.endTransaction(); } } else { t.setFoo(Integer.toString(i)) .setBar(-i); database.createNew(t); } } } catch (Exception e) { exception.set(e); } } }
package org.apache.james.transport.mailets; import java.io.*; import java.net.*; import java.util.*; import javax.mail.Address; import javax.mail.MessagingException; import javax.mail.Session; import javax.mail.Transport; import javax.mail.URLName; import javax.mail.SendFailedException; import javax.mail.internet.*; import org.apache.avalon.framework.component.ComponentException; import org.apache.avalon.framework.component.ComponentManager; import org.apache.avalon.framework.configuration.DefaultConfiguration; import org.apache.james.*; import org.apache.james.core.*; import org.apache.james.services.MailServer; import org.apache.james.services.MailStore; import org.apache.james.services.SpoolRepository; import org.apache.james.transport.*; import org.apache.mailet.*; public class RemoteDelivery extends GenericMailet implements Runnable { private SpoolRepository outgoing; private long delayTime = 21600000; // default is 6*60*60*1000 millis (6 hours) private int maxRetries = 5; // default number of retries private long smtpTimeout = 600000; //default number of ms to timeout on smtp delivery private int deliveryThreadCount = 1; // default number of delivery threads private String gatewayServer = null; // the server to send all email to private String gatewayPort = null; //the port of the gateway server to send all email to private Collection deliveryThreads = new Vector(); private MailServer mailServer; public void init() throws MessagingException { try { if (getInitParameter("delayTime") != null) { delayTime = Long.parseLong(getInitParameter("delayTime")); } } catch (Exception e) { log("Invalid delayTime setting: " + getInitParameter("delayTime")); } try { if (getInitParameter("maxRetries") != null) { maxRetries = Integer.parseInt(getInitParameter("maxRetries")); } } catch (Exception e) { log("Invalid maxRetries setting: " + getInitParameter("maxRetries")); } try { if (getInitParameter("timeout") != null) { smtpTimeout = Integer.parseInt(getInitParameter("timeout")); } } catch (Exception e) { log("Invalid timeout setting: " + getInitParameter("timeout")); } gatewayServer = getInitParameter("gateway"); gatewayPort = getInitParameter("gatewayPort"); ComponentManager compMgr = (ComponentManager)getMailetContext().getAttribute(Constants.AVALON_COMPONENT_MANAGER); String outgoingPath = getInitParameter("outgoing"); if (outgoingPath == null) { outgoingPath = "file:///../var/mail/outgoing"; } try { // Instantiate the a MailRepository for outgoing mails MailStore mailstore = (MailStore) compMgr.lookup("org.apache.james.services.MailStore"); DefaultConfiguration spoolConf = new DefaultConfiguration("repository", "generated:RemoteDelivery.java"); spoolConf.setAttribute("destinationURL", outgoingPath); spoolConf.setAttribute("type", "SPOOL"); outgoing = (SpoolRepository) mailstore.select(spoolConf); } catch (ComponentException cnfe) { log("Failed to retrieve Store component:" + cnfe.getMessage()); } catch (Exception e) { log("Failed to retrieve Store component:" + e.getMessage()); } //Start up a number of threads try { deliveryThreadCount = Integer.parseInt(getInitParameter("deliveryThreads")); } catch (Exception e) { } for (int i = 0; i < deliveryThreadCount; i++) { Thread t = new Thread(this, "Remote delivery thread (" + i + ")"); t.start(); deliveryThreads.add(t); } } private boolean deliver(MailImpl mail, Session session) { try { log("attempting to deliver " + mail.getName()); MimeMessage message = mail.getMessage(); //Create an array of the recipients as InternetAddress objects Collection recipients = mail.getRecipients(); InternetAddress addr[] = new InternetAddress[recipients.size()]; int j = 0; for (Iterator i = recipients.iterator(); i.hasNext(); j++) { MailAddress rcpt = (MailAddress)i.next(); addr[j] = rcpt.toInternetAddress(); } //Figure out which servers to try to send to. This collection // will hold all the possible target servers Collection targetServers = null; if (gatewayServer == null) { MailAddress rcpt = (MailAddress) recipients.iterator().next(); String host = rcpt.getHost(); //Lookup the possible targets targetServers = getMailetContext().getMailServers(host); if (targetServers.size() == 0) { log("No mail server found for: " + host); return failMessage(mail, new MessagingException("No route found to " + host), true); } } else { targetServers = new Vector(); targetServers.add(gatewayServer); } MessagingException lastError = null; if (addr.length > 0) { Iterator i = targetServers.iterator(); while ( i.hasNext()) { try { String outgoingmailserver = i.next().toString (); log("attempting delivery of " + mail.getName() + " to host " + outgoingmailserver + " to " + Arrays.asList(addr)); URLName urlname = new URLName("smtp://" + outgoingmailserver); Properties props = session.getProperties(); //This was an older version of JavaMail if (mail.getSender() == null) { props.put("mail.smtp.user", "<>"); props.put("mail.smtp.from", "<>"); } else { props.put("mail.smtp.user", mail.getSender().toString()); props.put("mail.smtp.from", mail.getSender().toString()); } //Many of these properties are only in later JavaMail versions //"mail.smtp.ehlo" //default true //"mail.smtp.auth" //default false //"mail.smtp.dsn.ret" //default to nothing... appended as RET= after MAIL FROM line. //"mail.smtp.dsn.notify" //default to nothing...appended as NOTIFY= after RCPT TO line. //"mail.smtp.localhost" //local server name, InetAddress.getLocalHost().getHostName(); Transport transport = session.getTransport(urlname); transport.connect(); transport.sendMessage(message, addr); transport.close(); log("mail (" + mail.getName() + ") sent successfully to " + outgoingmailserver); return true; } catch (SendFailedException sfe) { throw sfe; } catch (MessagingException me) { log("Exception delivering message (" + mail.getName() + ") - " + me.getMessage()); if (me.getNextException() != null && me.getNextException() instanceof java.io.IOException) { //This is more than likely a temporary failure lastError = me; continue; } else { return failMessage(mail, me, true); } } } // end while //If we encountered an exception while looping through, send the last exception we got if (lastError != null) { throw lastError; } } else { log("no recipients specified... not sure how this could have happened."); } } catch (SendFailedException sfe) { //Would like to log all the types of email addresses if (sfe.getValidSentAddresses() != null) { Address[] validSent = sfe.getValidSentAddresses(); Collection recipients = mail.getRecipients(); //Remove these addresses for the recipients for (int i = 0; i < validSent.length; i++) { try { MailAddress addr = new MailAddress(validSent[i].toString()); recipients.remove(addr); } catch (ParseException pe) { //ignore once debugging done pe.printStackTrace(); } } } return failMessage(mail, sfe, true); } catch (MessagingException ex) { //We should do a better job checking this... if the failure is a general //connect exception, this is less descriptive than more specific SMTP command //failure... have to lookup and see what are the various Exception //possibilities //Unable to deliver message after numerous tries... fail accordingly return failMessage(mail, ex, false); } return true; } private boolean failMessage(MailImpl mail, MessagingException ex, boolean permanent) { StringWriter sout = new StringWriter(); PrintWriter pout = new PrintWriter(sout, true); if (permanent) { pout.print("Permanent"); } else { pout.print("Temporary"); } pout.print(" exception delivering mail (" + mail.getName() + ": "); ex.printStackTrace(pout); log(sout.toString()); if (!permanent) { if (!mail.getState().equals(Mail.ERROR)) { mail.setState(Mail.ERROR); mail.setErrorMessage("0"); } int retries = Integer.parseInt(mail.getErrorMessage()); if (retries < maxRetries) { log("Storing message " + mail.getName() + " into outgoing after " + retries + " retries"); ++retries; mail.setErrorMessage(retries + ""); return false; } } bounce(mail, ex); return true; } private void bounce(MailImpl mail, MessagingException ex) { StringWriter sout = new StringWriter(); PrintWriter pout = new PrintWriter(sout, true); String machine ="[unknown]"; try{ InetAddress me = InetAddress.getLocalHost(); machine = me.getHostName(); }catch(Exception e){ machine = "[address unknown]"; } pout.println("Hi. This is the James mail server at " + machine + "."); pout.println("I'm afraid I wasn't able to deliver your message to the following addresses."); pout.println("This is a permanent error; I've given up. Sorry it didn't work out."); pout.println(); for (Iterator i = mail.getRecipients().iterator(); i.hasNext(); ) { pout.println(i.next()); } pout.println(ex.getMessage().trim()); pout.println(); pout.println("The original message is attached."); log("Sending failure message " + mail.getName()); try { getMailetContext().bounce(mail, sout.toString()); } catch (MessagingException me) { log("encountered unexpected messaging exception while bouncing message: " + me.getMessage()); } } public String getMailetInfo() { return "RemoteDelivery Mailet"; } /** * For this message, we take the list of recipients, organize these into distinct * servers, and duplicate the message for each of these servers, and then call * the deliver (messagecontainer) method for each server-specific * messagecontainer ... that will handle storing it in the outgoing queue if needed. * * @param mail org.apache.mailet.Mail * @return org.apache.mailet.MessageContainer */ public void service(Mail genericmail) throws AddressException { MailImpl mail = (MailImpl)genericmail; //Do I want to give the internal key, or the message's Message ID log("Remotely delivering mail " + mail.getName()); Collection recipients = mail.getRecipients(); //Must first organize the recipients into distinct servers (name made case insensitive) Hashtable targets = new Hashtable(); for (Iterator i = recipients.iterator(); i.hasNext();) { MailAddress target = (MailAddress)i.next(); String targetServer = target.getHost().toLowerCase(); Collection temp = (Collection)targets.get(targetServer); if (temp == null) { temp = new Vector(); targets.put(targetServer, temp); } temp.add(target); } //We have the recipients organized into distinct servers... put them into the //delivery store organized like this... this is ultra inefficient I think... //store the new message containers, organized by server, in the outgoing mail repository String name = mail.getName(); for (Iterator i = targets.keySet().iterator(); i.hasNext(); ) { String host = (String) i.next(); Collection rec = (Collection)targets.get(host); log("sending mail to " + rec + " on " + host); mail.setRecipients(rec); mail.setName(name + "-to-" + host); outgoing.store(mail); //Set it to try to deliver (in a separate thread) immediately (triggered by storage) } mail.setState(Mail.GHOST); } public void destroy() { //Wake up all threads from waiting for an accept notifyAll(); for (Iterator i = deliveryThreads.iterator(); i.hasNext(); ) { Thread t = (Thread)i.next(); t.interrupt(); } } /** * Handles checking the outgoing spool for new mail and delivering them if * there are any */ public void run() { //Checks the pool and delivers a mail message Properties props = new Properties(); //Not needed for production environment props.put("mail.debug", "false"); //Prevents problems encountered with 250 OK Messages props.put("mail.smtp.ehlo", "false"); //Sets timeout on going connections props.put("mail.smtp.timeout", smtpTimeout + ""); //If there's a gateway port, we can just set it here if (gatewayPort != null) { props.put("mail.smtp.port", gatewayPort); } Session session = Session.getInstance(props, null); while (!Thread.currentThread().interrupted()) { try { String key = outgoing.accept(delayTime); log(Thread.currentThread().getName() + " will process mail " + key); MailImpl mail = outgoing.retrieve(key); if (deliver(mail, session)) { //Message was successfully delivered/fully failed... delete it outgoing.remove(key); } else { //Something happened that will delay delivery. Store any updates outgoing.store(mail); } //Clear the object handle to make sure it recycles this object. mail = null; } catch (Exception e) { log("Exception caught in RemoteDelivery.run(): " + e); } } } }
package org.granite.grails.integration; import java.beans.BeanInfo; import java.beans.Introspector; import java.beans.PropertyDescriptor; import java.lang.reflect.Method; import java.lang.reflect.Type; import org.granite.hibernate4.ProxyFactory; /** * @author Franck WOLFF */ public class GrailsProxyFactory extends ProxyFactory { public GrailsProxyFactory(String initializerClassName) { super(initializerClassName); } @Override protected Object[] getIdentifierInfo(Class<?> persistentClass) { Object[] infos = identifierInfos.get(persistentClass); if (infos != null) return infos; Type type = null; Method getter = null; PropertyDescriptor[] propertyDescriptors = null; try { BeanInfo info = Introspector.getBeanInfo(persistentClass); propertyDescriptors = info.getPropertyDescriptors(); } catch (Exception e) { throw new IllegalArgumentException("Could not find id in: " + persistentClass, e); } for (PropertyDescriptor propertyDescriptor : propertyDescriptors) { Method method = propertyDescriptor.getReadMethod(); if (method != null && "getId".equals(method.getName())) { getter = method; type = method.getGenericReturnType(); break; } } if (type != null) { infos = new Object[] { type, getter }; Object[] previousInfos = identifierInfos.putIfAbsent(persistentClass, infos); if (previousInfos != null) infos = previousInfos; // should be the same... return infos; } throw new IllegalArgumentException("Could not find id in: " + persistentClass); } }
package online.zhaopei.myproject.constant; import java.io.Serializable; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; public enum CommonConstant implements Serializable { DEFAULT_PAGE_ZIZE("10"), WECHAT_APP_ID("wx8a3ecd5dc8bf14ac"), WECHAT_APP_SECRET("0383851a42499e5e72e1d09407d9d6e6"), ; private static Map<String, String> COUNTRY_MAP = new HashMap<String, String>(); private static Map<String, String> CURRENCY_MAP = new HashMap<String, String>(); private static Map<String, String> UNIT_MAP = new HashMap<String, String>(); private static Map<String, String> CUSTOMS_MAP = new HashMap<String, String>(); private static Map<String, String> ZBXC_CUSTOMS_MAP = new HashMap<String, String>(); private static Map<String, String> WRAP_TYPE_MAP = new HashMap<String, String>(); private static Map<String, String> TRAF_MODE_MAP = new HashMap<String, String>(); private static Map<String, String> TRADE_MODE_MAP = new HashMap<String, String>(); private static Map<String, String> ZBXC_TRADE_MODE_MAP = new HashMap<String, String>(); private static Map<String, String> TRAF_NO_MAP = new HashMap<String, String>(); private static Map<String, String> ID_TYPE_MAP = new HashMap<String, String>(); private static Map<String, String> IE_TYPE_MAP = new HashMap<String, String>(); private static Map<String, String> APP_TYPE_MAP = new HashMap<String, String>(); private static List<String> PIE_COLORS = new ArrayList<String>(); public static byte BOM[] = {(byte)0xEF, (byte)0xBB, (byte)0xBF}; public static int XLS_MAX_LINE = 65000; private String value; static { ID_TYPE_MAP.put("", ""); ID_TYPE_MAP.put("1", ""); ID_TYPE_MAP.put("2", ""); ID_TYPE_MAP.put("3", ""); ID_TYPE_MAP.put("4", ""); APP_TYPE_MAP.put("", ""); APP_TYPE_MAP.put("1", ""); APP_TYPE_MAP.put("2", ""); APP_TYPE_MAP.put("3", ""); ZBXC_CUSTOMS_MAP.put("", ""); ZBXC_CUSTOMS_MAP.put("4604", ""); ZBXC_CUSTOMS_MAP.put("4605", ""); ZBXC_CUSTOMS_MAP.put("4606", ""); ZBXC_CUSTOMS_MAP.put("4612", ""); ZBXC_CUSTOMS_MAP.put("4619", ""); ZBXC_CUSTOMS_MAP.put("4620", ""); PIE_COLORS.add("#455C73"); PIE_COLORS.add("#9B59B6"); PIE_COLORS.add("#BDC3C7"); PIE_COLORS.add("#26B99A"); PIE_COLORS.add("#3498DB"); PIE_COLORS.add("#E74C3C"); PIE_COLORS.add("#EC971F"); PIE_COLORS.add("#DE18CA"); ZBXC_TRADE_MODE_MAP.put("", ""); ZBXC_TRADE_MODE_MAP.put("1210", ""); ZBXC_TRADE_MODE_MAP.put("9610", ""); IE_TYPE_MAP.put("", ""); IE_TYPE_MAP.put("I", ""); IE_TYPE_MAP.put("E", ""); } private CommonConstant(String value) { this.value = value; } @Override public String toString() { return this.value; } public static Map<String, String> getCOUNTRY_MAP() { return COUNTRY_MAP; } public static Map<String, String> getCURRENCY_MAP() { return CURRENCY_MAP; } public static Map<String, String> getUNIT_MAP() { return UNIT_MAP; } public static Map<String, String> getCUSTOMS_MAP() { return CUSTOMS_MAP; } public static Map<String, String> getWRAP_TYPE_MAP() { return WRAP_TYPE_MAP; } public static Map<String, String> getTRAF_MODE_MAP() { return TRAF_MODE_MAP; } public static Map<String, String> getTRADE_MODE_MAP() { return TRADE_MODE_MAP; } public static Map<String, String> getTRAF_NO_MAP() { return TRAF_NO_MAP; } public static Map<String, String> getAPP_TYPE_MAP() { return APP_TYPE_MAP; } public static Map<String, String> getID_TYPE_MAP() { return ID_TYPE_MAP; } public static List<String> getPIE_COLORS() { return PIE_COLORS; } public static Map<String, String> getZBXC_CUSTOMS_MAP() { return ZBXC_CUSTOMS_MAP; } public static Map<String, String> getZBXC_TRADE_MODE_MAP() { return ZBXC_TRADE_MODE_MAP; } public static Map<String, String> getIE_TYPE_MAP() { return IE_TYPE_MAP; } }
package org.jivesoftware.messenger.handler; import org.jivesoftware.messenger.*; import org.jivesoftware.messenger.auth.UnauthorizedException; import org.jivesoftware.messenger.user.User; import org.jivesoftware.messenger.user.UserManager; import org.jivesoftware.messenger.user.UserNotFoundException; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Collection; import org.dom4j.DocumentHelper; import org.dom4j.Element; import org.dom4j.QName; import org.xmpp.packet.IQ; import org.xmpp.packet.JID; import org.xmpp.packet.PacketError; /** * Implements the TYPE_IQ vcard-temp protocol. Clients * use this protocol to set and retrieve the vCard information * associated with someone's account. * <p/> * A 'get' query retrieves the vcard for the addressee. * A 'set' query sets the vcard information for the sender's account. * <p/> * Currently an empty implementation to allow usage with normal * clients. Future implementation needed. * <p/> * <h2>Assumptions</h2> * This handler assumes that the request is addressed to the server. * An appropriate TYPE_IQ tag matcher should be placed in front of this * one to route TYPE_IQ requests not addressed to the server to * another channel (probably for direct delivery to the recipient). * <p/> * <h2>Warning</h2> * There should be a way of determining whether a session has * authorization to access this feature. I'm not sure it is a good * idea to do authorization in each handler. It would be nice if * the framework could assert authorization policies across channels. * <p/> * <h2>Warning</h2> * I have noticed incompatibility between vCard XML used by Exodus and Psi. * There is a new vCard standard going through the JSF JEP process. We might * want to start either standardizing on clients (probably the most practical), * sending notices for non-conformance (useful), * or attempting to translate between client versions (not likely). * * @author Iain Shigeoka */ public class IQvCardHandler extends IQHandler { private IQHandlerInfo info; private UserManager userManager; public IQvCardHandler() { super("XMPP vCard Handler"); info = new IQHandlerInfo("vCard", "vcard-temp"); } public IQ handleIQ(IQ packet) throws UnauthorizedException, PacketException { IQ result = null; try { JID recipient = packet.getTo(); IQ.Type type = packet.getType(); if (type.equals(IQ.Type.set)) { User user = userManager.getUser(packet.getFrom().getNode()); // Proper format Element vcard = packet.getChildElement(); if (vcard != null) { List nameStack = new ArrayList(5); readVCard(vcard, nameStack, user); } result = IQ.createResultIQ(packet); } else if (type.equals(IQ.Type.get)) { result = IQ.createResultIQ(packet); Element vcard = DocumentHelper.createElement(QName.get("vCard", "vcard-temp")); result.setChildElement(vcard); // Only try to get the vCard values of non-anonymous users if (recipient != null && recipient.getNode() != null) { User user = userManager.getUser(recipient.getNode()); VCardManager vManager = VCardManager.getInstance(); Collection<String> names = vManager.getVCardPropertyNames(user.getUsername()); for (String name : names) { String path = name.replace(':', '/'); Element node = DocumentHelper.makeElement(vcard, path); node.setText(vManager.getVCardProperty(user.getUsername(), name)); } } } else { result = IQ.createResultIQ(packet); result.setChildElement(packet.getChildElement().createCopy()); result.setError(PacketError.Condition.not_acceptable); } } catch (UserNotFoundException e) { result = IQ.createResultIQ(packet); result.setChildElement(packet.getChildElement().createCopy()); result.setError(PacketError.Condition.item_not_found); } return result; } /** * We need to build names from heirarchical position in the DOM tree. * * @param element The element to interrogate for text nodes * @param nameStack The current name of the vcard property (list as a stack) * @param user the user getting their vcard set */ private void readVCard(Element element, List nameStack, User user) throws UnauthorizedException { Iterator children = element.elementIterator(); while (children.hasNext()) { Element child = (Element)children.next(); nameStack.add(child.getName()); String value = child.getTextTrim(); if (value != null) { if (!"".equals(value)) { VCardManager.getInstance().setVCardProperty(user.getUsername(), createName(nameStack), value); } } readVCard(child, nameStack, user); nameStack.remove(nameStack.size() - 1); } } /** * Generate a name for the given name stack values * * @param nameStack * @return The name concatenating the values with the ':' character */ private String createName(List nameStack) { StringBuilder buf = new StringBuilder(); Iterator iter = nameStack.iterator(); while (iter.hasNext()) { if (buf.length() > 0) { buf.append(':'); } buf.append(iter.next()); } return buf.toString(); } public void initialize(XMPPServer server) { super.initialize(server); userManager = server.getUserManager(); } public IQHandlerInfo getInfo() { return info; } }
package org.egordorichev.lasttry.world.gen; import java.io.File; import java.io.FileNotFoundException; import org.egordorichev.lasttry.LastTry; import org.egordorichev.lasttry.item.Item; import org.egordorichev.lasttry.item.ItemID; import org.egordorichev.lasttry.item.blocks.Block; import org.egordorichev.lasttry.item.blocks.Wall; import org.egordorichev.lasttry.util.FileReader; import org.egordorichev.lasttry.util.FileWriter; import org.egordorichev.lasttry.world.World; import org.egordorichev.lasttry.world.World.EvilType; import org.egordorichev.lasttry.world.tile.TileData; public class WorldProvider { /** * Generate a world with the given name, width, and height. * * @param name * Name of the world. * @param width * Width of the world. * @param height * Height of the workd. * @return New world. */ public static World generate(String name, int width, int height) { LastTry.log("Generating..."); // Create 2D array of tile ID's. // Then populate the array. // TODO: Create a decent plugin-like system for world generation // allow for users to share their generation systems IWorldGenerator gen = new SimpleWorldGen(); int tileIDs[][] = gen.generate(width, height); // Convert the 2D tile ID array to a 1D array of TileData int totalSize = width * height; TileData[] data = new TileData[totalSize]; for (int y = 0; y < height; y++) { for (int x = 0; x < width; x++) { int id = tileIDs[x][y]; data[x + y * width] = new TileData((Block) Item.fromID(id), Wall.getForBlockID(id)); } } // Create the world and return World world = new World(name, width, height, data); LastTry.log("Finished generating!"); return world; } /** * Save the given world. * * @param world * World to save. */ public static void save(World world) { LastTry.log("Saving..."); FileWriter stream = new FileWriter(getFilePath(world.getName())); int width = world.getWidth(); int height = world.getHeight(); // Header stream.writeInt32(world.getVersion()); // Basic world info: // name, width/height & evil type, etc. stream.writeString(world.getName()); stream.writeInt32(width); stream.writeInt32(height); stream.writeBoolean(world.isExpert()); stream.writeBoolean((world.getEvilType() == EvilType.CRIMSON) ? true : false); // Tile data int totalSize = width * height; for (int i = 0; i < totalSize; i++) { TileData data = world.getTileData(i); int blockId = 0; int wallId = 0; if (data.block != null) { blockId = data.block.getId(); } if (data.wall != null) { wallId = data.wall.getId(); } stream.writeInt32(blockId); stream.writeInt32(wallId); // TODO: RLE } stream.close(); LastTry.log("Done saving!"); } /** * Load a world by the given name. Returns null if the world cannot be * found. * * @param worldName * World to load. * @return World by name. */ public static World load(String worldName) { LastTry.log("Loading..."); try { FileReader stream = new FileReader(getFilePath(worldName)); // Version header, check if compatible int version = stream.readInt32(); if (version > World.CURRENT_VERSION) { throw new RuntimeException("Unsupported version"); } else if (version < World.CURRENT_VERSION) { LastTry.log("Warning: Attempting to load outdated world format."); } // Basic world info: // name, width/height & evil type, etc. worldName = stream.readString(); int width = stream.readInt32(); int height = stream.readInt32(); boolean expert = stream.readBoolean(); EvilType evilType = (stream.readBoolean()) ? EvilType.CRIMSON : EvilType.CORRUPTION; // Tile data int totalSize = width * height; TileData[] tiles = new TileData[totalSize]; for (int i = 0; i < totalSize; i++) { tiles[i] = new TileData((Block) Item.fromID(stream.readInt32()), (Wall) Item.fromID(stream.readInt32())); // TODO: RLE } stream.close(); LastTry.log("Done loading!"); World world = new World(worldName, width, height, evilType, tiles); world.setExpert(expert); } catch (FileNotFoundException exception) { // world.save(); LastTry.handleException(exception); System.exit(0); } return null; } /** * Checks if a world by the given name exists and if it is valid to load. * * @param worldName * World to load. * @return */ public static boolean exists(String worldName) { File worldFile = new File(worldName); if (!worldFile.exists()) { return false; } // TODO: Simple check to see if it exists // TODO: Check if exists but is incompatible (Check world version but // nothing else) if (worldFile.length() == 0) { return false; } return true; } /** * Get the file path of a world by the given name. * * @param worldName * World name. * @return Path to world file. */ private static String getFilePath(String worldName) { return "assets/worlds/" + worldName + ".wld"; } }
package org.jboss.netty.handler.timeout; import java.util.ArrayList; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.concurrent.Executors; import java.util.concurrent.ThreadFactory; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.locks.ReadWriteLock; import java.util.concurrent.locks.ReentrantReadWriteLock; import org.jboss.netty.logging.InternalLogger; import org.jboss.netty.logging.InternalLoggerFactory; import org.jboss.netty.util.ConcurrentIdentityHashMap; import org.jboss.netty.util.MapBackedSet; import org.jboss.netty.util.ReusableIterator; import org.jboss.netty.util.ThreadRenamingRunnable; /** * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * @version $Rev$, $Date$ */ public class HashedWheelTimer implements Timer { static final InternalLogger logger = InternalLoggerFactory.getInstance(HashedWheelTimer.class); private static final AtomicInteger id = new AtomicInteger(); private final Worker worker = new Worker(); final Thread workerThread; final AtomicBoolean shutdown = new AtomicBoolean(); private final long roundDuration; final long tickDuration; final Set<HashedWheelTimeout>[] wheel; final ReusableIterator<HashedWheelTimeout>[] iterators; final int mask; final ReadWriteLock lock = new ReentrantReadWriteLock(); volatile int wheelCursor; public HashedWheelTimer() { this(Executors.defaultThreadFactory()); } public HashedWheelTimer( long tickDuration, TimeUnit unit, int ticksPerWheel) { this(Executors.defaultThreadFactory(), tickDuration, unit, ticksPerWheel); } public HashedWheelTimer(ThreadFactory threadFactory) { this(threadFactory, 100, TimeUnit.MILLISECONDS, 512); // about 50 sec } public HashedWheelTimer( ThreadFactory threadFactory, long tickDuration, TimeUnit unit, int ticksPerWheel) { if (threadFactory == null) { throw new NullPointerException("threadFactory"); } if (unit == null) { throw new NullPointerException("unit"); } if (tickDuration <= 0) { throw new IllegalArgumentException( "tickDuration must be greater than 0: " + tickDuration); } if (ticksPerWheel <= 0) { throw new IllegalArgumentException( "ticksPerWheel must be greater than 0: " + ticksPerWheel); } // Normalize ticksPerWheel to power of two and initialize the wheel. wheel = createWheel(ticksPerWheel); iterators = createIterators(wheel); mask = wheel.length - 1; // Convert checkInterval to nanoseconds. this.tickDuration = tickDuration = unit.toMillis(tickDuration); // Prevent overflow. if (tickDuration == Long.MAX_VALUE || tickDuration >= Long.MAX_VALUE / wheel.length) { throw new IllegalArgumentException( "tickDuration is too long: " + tickDuration + ' ' + unit); } roundDuration = tickDuration * wheel.length; workerThread = threadFactory.newThread(new ThreadRenamingRunnable( worker, "Hashed wheel timer #" + id.incrementAndGet())); } @SuppressWarnings("unchecked") private static Set<HashedWheelTimeout>[] createWheel(int ticksPerWheel) { if (ticksPerWheel <= 0) { throw new IllegalArgumentException( "ticksPerWheel must be greater than 0: " + ticksPerWheel); } if (ticksPerWheel > 1073741824) { throw new IllegalArgumentException( "ticksPerWheel may not be greater than 2^30: " + ticksPerWheel); } ticksPerWheel = normalizeTicksPerWheel(ticksPerWheel); Set<HashedWheelTimeout>[] wheel = new Set[ticksPerWheel]; for (int i = 0; i < wheel.length; i ++) { wheel[i] = new MapBackedSet<HashedWheelTimeout>( new ConcurrentIdentityHashMap<HashedWheelTimeout, Boolean>(16, 0.95f, 4)); } return wheel; } @SuppressWarnings("unchecked") private static ReusableIterator<HashedWheelTimeout>[] createIterators(Set<HashedWheelTimeout>[] wheel) { ReusableIterator<HashedWheelTimeout>[] iterators = new ReusableIterator[wheel.length]; for (int i = 0; i < wheel.length; i ++) { iterators[i] = (ReusableIterator<HashedWheelTimeout>) wheel[i].iterator(); } return iterators; } private static int normalizeTicksPerWheel(int ticksPerWheel) { int normalizedTicksPerWheel = 1; while (normalizedTicksPerWheel < ticksPerWheel) { normalizedTicksPerWheel <<= 1; } return normalizedTicksPerWheel; } public void start() { workerThread.start(); } public Set<Timeout> stop() { if (!shutdown.compareAndSet(false, true)) { return Collections.emptySet(); } while (workerThread.isAlive()) { workerThread.interrupt(); try { workerThread.join(100); } catch (InterruptedException e) { // Ignore } } Set<Timeout> unprocessedTimeouts = new HashSet<Timeout>(); for (Set<HashedWheelTimeout> bucket: wheel) { unprocessedTimeouts.addAll(bucket); bucket.clear(); } return Collections.unmodifiableSet(unprocessedTimeouts); } public Timeout newTimeout(TimerTask task, long delay, TimeUnit unit) { final long currentTime = System.currentTimeMillis(); if (task == null) { throw new NullPointerException("task"); } if (unit == null) { throw new NullPointerException("unit"); } delay = unit.toMillis(delay); if (delay < tickDuration) { delay = tickDuration; } if (!workerThread.isAlive()) { start(); } // Prepare the required parameters to create the timeout object. HashedWheelTimeout timeout; final long lastRoundDelay = delay % roundDuration; final long lastTickDelay = delay % tickDuration; final long relativeIndex = lastRoundDelay / tickDuration + (lastTickDelay != 0? 1 : 0); final long deadline = currentTime + delay; final long remainingRounds = delay / roundDuration - (delay % roundDuration == 0? 1 : 0); // Add the timeout to the wheel. lock.readLock().lock(); try { timeout = new HashedWheelTimeout( task, deadline, (int) (wheelCursor + relativeIndex & mask), remainingRounds); wheel[timeout.stopIndex].add(timeout); } finally { lock.readLock().unlock(); } return timeout; } private final class Worker implements Runnable { private long startTime; private long tick; Worker() { super(); } public void run() { List<HashedWheelTimeout> expiredTimeouts = new ArrayList<HashedWheelTimeout>(); startTime = System.currentTimeMillis(); tick = 1; while (!shutdown.get()) { waitForNextTick(); fetchExpiredTimeouts(expiredTimeouts); notifyExpiredTimeouts(expiredTimeouts); } } private void fetchExpiredTimeouts( List<HashedWheelTimeout> expiredTimeouts) { // Find the expired timeouts and decrease the round counter // if necessary. Note that we don't send the notification // immediately to make sure the listeners are called without // an exclusive lock. lock.writeLock().lock(); try { int oldBucketHead = wheelCursor; int newBucketHead = oldBucketHead + 1 & mask; wheelCursor = newBucketHead; ReusableIterator<HashedWheelTimeout> i = iterators[oldBucketHead]; fetchExpiredTimeouts(expiredTimeouts, i); } finally { lock.writeLock().unlock(); } } private void fetchExpiredTimeouts( List<HashedWheelTimeout> expiredTimeouts, ReusableIterator<HashedWheelTimeout> i) { long currentTime = System.currentTimeMillis(); i.rewind(); while (i.hasNext()) { HashedWheelTimeout timeout = i.next(); synchronized (timeout) { if (timeout.remainingRounds <= 0) { if (timeout.deadline <= currentTime) { i.remove(); expiredTimeouts.add(timeout); } else { // A rare case where a timeout is put for the next // round: just wait for the next round. } } else { timeout.remainingRounds } } } } private void notifyExpiredTimeouts( List<HashedWheelTimeout> expiredTimeouts) { // Notify the expired timeouts. for (int i = expiredTimeouts.size() - 1; i >= 0; i expiredTimeouts.get(i).expire(); } // Clean up the temporary list. expiredTimeouts.clear(); } private void waitForNextTick() { for (;;) { final long currentTime = System.currentTimeMillis(); final long sleepTime = tickDuration * tick - (currentTime - startTime); if (sleepTime <= 0) { break; } try { Thread.sleep(sleepTime / 1000000, (int) (sleepTime % 1000000)); } catch (InterruptedException e) { if (shutdown.get()) { return; } } } // Reset the tick if overflow is expected. if (tickDuration * tick > Long.MAX_VALUE - tickDuration) { startTime = System.currentTimeMillis(); tick = 1; } else { // Increase the tick if overflow is not likely to happen. tick ++; } } } private final class HashedWheelTimeout implements Timeout { private final TimerTask task; final int stopIndex; final long deadline; volatile long remainingRounds; private volatile boolean cancelled; HashedWheelTimeout( TimerTask task, long deadline, int stopIndex, long remainingRounds) { this.task = task; this.deadline = deadline; this.stopIndex = stopIndex; this.remainingRounds = remainingRounds; } public TimerTask getTask() { return task; } public void cancel() { if (isExpired()) { return; } cancelled = true; // Might be called more than once, but doesn't matter. wheel[stopIndex].remove(this); } public boolean isCancelled() { return cancelled; } public boolean isExpired() { return cancelled || System.currentTimeMillis() > deadline; } public void expire() { if (cancelled) { return; } try { task.run(this); } catch (Throwable t) { logger.warn( "An exception was thrown by " + TimerTask.class.getSimpleName() + ".", t); } } @Override public String toString() { long currentTime = System.currentTimeMillis(); long remaining = deadline - currentTime; StringBuilder buf = new StringBuilder(192); buf.append(getClass().getSimpleName()); buf.append('('); buf.append("deadline: "); if (remaining > 0) { buf.append(remaining / 1000000); buf.append(" ms later, "); } else if (remaining < 0) { buf.append(-remaining / 1000000); buf.append(" ms ago, "); } else { buf.append("now, "); } if (isCancelled()) { buf.append (", cancelled"); } return buf.append(')').toString(); } } }
package org.jenkinsci.remoting.engine; import java.security.cert.X509Certificate; import javax.annotation.Nonnull; /** * Represents a database of clients that are permitted to connect. * * @since FIXME */ public abstract class JnlpClientDatabase { /** * Check if the supplied client name exists. * @param clientName the client name. * @return {@code true} if and only if the named client exists. */ public abstract boolean exists(String clientName); /** * Gets the secret for the supplied client name. * @param clientName the client name. * @return the secret or {@code null}. Should not return {@code null} if {@link #exists(String)} but this may occur * if there is a race between establishing a connection and the client being removed from the database. */ public abstract String getSecretOf(@Nonnull String clientName); /** * Performs client certificate validation. * @param clientName the client name. * @param certificate the certificate. * @return the validation. */ @Nonnull public ValidationResult validateCertificate(@Nonnull String clientName, @Nonnull X509Certificate certificate) { return ValidationResult.UNCHECKED; } /** * The types of certificate validation results. */ public enum ValidationResult { /** * The certificate is invalid, reject the connection. */ INVALID, /** * The certificate was not checked, fall back to secret validation. */ UNCHECKED, /** * The certificate is valid, but check the secret also. */ REVERIFY_SECRET, /** * The certificate is valid and proven to originate from the named client, skip secret validation. */ IDENTITY_PROVED; } }
package org.jreactive.iso8583.netty.codec; import com.solab.iso8583.IsoMessage; import com.solab.iso8583.MessageFactory; import io.netty.buffer.ByteBuf; import io.netty.channel.ChannelHandlerContext; import io.netty.handler.codec.ByteToMessageDecoder; import java.util.List; public class Iso8583Decoder extends ByteToMessageDecoder { private final MessageFactory messageFactory; public Iso8583Decoder(MessageFactory messageFactory) { this.messageFactory = messageFactory; } @Override protected void decode(ChannelHandlerContext ctx, ByteBuf byteBuf, List out) throws Exception { //message body starts immediately, no length header byte[] bytes = new byte[byteBuf.readableBytes()]; byteBuf.readBytes(bytes); final IsoMessage isoMessage = messageFactory.parseMessage(bytes, 0); if (isoMessage != null) { //noinspection unchecked out.add(isoMessage); } } }
package org.komamitsu.fluency.buffer; import com.fasterxml.jackson.databind.ObjectMapper; import org.komamitsu.fluency.sender.Sender; import org.msgpack.core.MessagePack; import org.msgpack.core.MessagePacker; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.nio.ByteBuffer; import java.util.Arrays; import java.util.HashMap; import java.util.Map; import java.util.UUID; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.atomic.AtomicLong; public class PackedForwardBuffer extends Buffer<PackedForwardBuffer.Config> { private static final Logger LOG = LoggerFactory.getLogger(PackedForwardBuffer.class); private final Map<String, RetentionBuffer> retentionBuffers = new HashMap<String, RetentionBuffer>(); private final LinkedBlockingQueue<TaggableBuffer> flushableBuffers = new LinkedBlockingQueue<TaggableBuffer>(); private final BufferPool bufferPool; private PackedForwardBuffer(PackedForwardBuffer.Config bufferConfig) { super(bufferConfig); bufferPool = new BufferPool(bufferConfig.getInitialBufferSize(), bufferConfig.getMaxBufferSize()); } private RetentionBuffer prepareBuffer(String tag, int writeSize) throws BufferFullException { RetentionBuffer retentionBuffer = retentionBuffers.get(tag); if (retentionBuffer != null && retentionBuffer.getByteBuffer().remaining() > writeSize) { return retentionBuffer; } int newRetentionBufferSize; if (retentionBuffer == null) { newRetentionBufferSize = bufferConfig.getInitialBufferSize(); } else{ newRetentionBufferSize = (int) (retentionBuffer.getByteBuffer().capacity() * bufferConfig.getBufferExpandRatio()); } while (newRetentionBufferSize < writeSize) { newRetentionBufferSize *= bufferConfig.getBufferExpandRatio(); } ByteBuffer acquiredBuffer = bufferPool.acquireBuffer(newRetentionBufferSize); if (acquiredBuffer == null) { throw new BufferFullException("Buffer is full. bufferConfig=" + bufferConfig + ", bufferPool=" + bufferPool); } RetentionBuffer newBuffer = new RetentionBuffer(acquiredBuffer); if (retentionBuffer != null) { retentionBuffer.getByteBuffer().flip(); newBuffer.getByteBuffer().put(retentionBuffer.getByteBuffer()); bufferPool.returnBuffer(retentionBuffer.getByteBuffer()); } LOG.trace("prepareBuffer(): allocate a new buffer. tag={}, buffer={}", tag, newBuffer); retentionBuffers.put(tag, newBuffer); return newBuffer; } @Override public void append(String tag, long timestamp, Map<String, Object> data) throws IOException { ObjectMapper objectMapper = objectMapperHolder.get(); ByteArrayOutputStream outputStream = outputStreamHolder.get(); outputStream.reset(); objectMapper.writeValue(outputStream, Arrays.asList(timestamp, data)); outputStream.close(); synchronized (retentionBuffers) { RetentionBuffer buffer = prepareBuffer(tag, outputStream.size()); buffer.getByteBuffer().put(outputStream.toByteArray()); buffer.getLastUpdatedTimeMillis().set(System.currentTimeMillis()); moveRetentionBufferIfNeeded(tag, buffer); } } private void moveRetentionBufferIfNeeded(String tag, RetentionBuffer buffer) throws IOException { if (buffer.getByteBuffer().position() > bufferConfig.getBufferRetentionSize()) { moveRetentionBufferToFlushable(tag, buffer); } } private void moveRetentionBuffersToFlushable(boolean force) throws IOException { long expiredThreshold = System.currentTimeMillis() - bufferConfig.getBufferRetentionTimeMillis(); synchronized (retentionBuffers) { for (Map.Entry<String, RetentionBuffer> entry : retentionBuffers.entrySet()) { // it can be null because moveRetentionBufferToFlushable() can set null if (entry.getValue() != null) { if (force || entry.getValue().getLastUpdatedTimeMillis().get() < expiredThreshold) { moveRetentionBufferToFlushable(entry.getKey(), entry.getValue()); } } } } } private void moveRetentionBufferToFlushable(String tag, RetentionBuffer buffer) throws IOException { try { LOG.trace("moveRetentionBufferToFlushable(): tag={}, buffer={}", tag, buffer); flushableBuffers.put(new TaggableBuffer(tag, buffer.getByteBuffer())); retentionBuffers.put(tag, null); } catch (InterruptedException e) { throw new IOException("Failed to move retention buffer due to interruption", e); } } @Override public void flushInternal(Sender sender, boolean force) throws IOException { moveRetentionBuffersToFlushable(force); TaggableBuffer flushableBuffer = null; while ((flushableBuffer = flushableBuffers.poll()) != null) { try { // TODO: Reuse MessagePacker ByteArrayOutputStream header = new ByteArrayOutputStream(); MessagePacker messagePacker = MessagePack.newDefaultPacker(header); LOG.trace("flushInternal(): bufferUsage={}, flushableBuffer={}", getBufferUsage(), flushableBuffer); String tag = flushableBuffer.getTag(); ByteBuffer byteBuffer = flushableBuffer.getByteBuffer(); if (bufferConfig.isAckResponseMode()) { messagePacker.packArrayHeader(3); } else { messagePacker.packArrayHeader(2); } messagePacker.packString(tag); messagePacker.packRawStringHeader(byteBuffer.position()); messagePacker.flush(); synchronized (sender) { ByteBuffer headerBuffer = ByteBuffer.wrap(header.toByteArray()); byteBuffer.flip(); if (bufferConfig.isAckResponseMode()) { String uuid = UUID.randomUUID().toString(); sender.sendWithAck(Arrays.asList(headerBuffer, byteBuffer), uuid.getBytes(CHARSET)); } else { sender.send(Arrays.asList(headerBuffer, byteBuffer)); } } } finally { bufferPool.returnBuffer(flushableBuffer.getByteBuffer()); } } } @Override public synchronized void closeInternal(Sender sender) throws IOException { moveRetentionBuffersToFlushable(true); retentionBuffers.clear(); flush(sender, true); bufferPool.releaseBuffers(); } @Override public long getAllocatedSize() { return bufferPool.getAllocatedSize(); } private static class RetentionBuffer { private final AtomicLong lastUpdatedTimeMillis = new AtomicLong(); private final ByteBuffer byteBuffer; public RetentionBuffer(ByteBuffer byteBuffer) { this.byteBuffer = byteBuffer; } public AtomicLong getLastUpdatedTimeMillis() { return lastUpdatedTimeMillis; } public ByteBuffer getByteBuffer() { return byteBuffer; } @Override public String toString() { return "ExpirableBuffer{" + "lastUpdatedTimeMillis=" + lastUpdatedTimeMillis + ", byteBuffer=" + byteBuffer + '}'; } } private static class TaggableBuffer { private final String tag; private final ByteBuffer byteBuffer; public TaggableBuffer(String tag, ByteBuffer byteBuffer) { this.tag = tag; this.byteBuffer = byteBuffer; } public String getTag() { return tag; } public ByteBuffer getByteBuffer() { return byteBuffer; } @Override public String toString() { return "TaggableBuffer{" + "tag='" + tag + '\'' + ", byteBuffer=" + byteBuffer + '}'; } } public static class Config extends Buffer.Config<PackedForwardBuffer, Config> { private int initialBufferSize = 1024 * 1024; private float bufferExpandRatio = 2.0f; private int bufferRetentionSize = 4 * 1024 * 1024; private int bufferRetentionTimeMillis = 400; public int getInitialBufferSize() { return initialBufferSize; } public Config setInitialBufferSize(int initialBufferSize) { this.initialBufferSize = initialBufferSize; return this; } public float getBufferExpandRatio() { return bufferExpandRatio; } public Config setBufferExpandRatio(float bufferExpandRatio) { this.bufferExpandRatio = bufferExpandRatio; return this; } public int getBufferRetentionSize() { return bufferRetentionSize; } public Config setBufferRetentionSize(int bufferRetentionSize) { this.bufferRetentionSize = bufferRetentionSize; return this; } public int getBufferRetentionTimeMillis() { return bufferRetentionTimeMillis; } public Config setBufferRetentionTimeMillis(int bufferRetentionTimeMillis) { this.bufferRetentionTimeMillis = bufferRetentionTimeMillis; return this; } @Override public String toString() { return "Config{" + "initialBufferSize=" + initialBufferSize + ", bufferExpandRatio=" + bufferExpandRatio + ", bufferRetentionSize=" + bufferRetentionSize + ", bufferRetentionTimeMillis=" + bufferRetentionTimeMillis + "} " + super.toString(); } @Override public PackedForwardBuffer createInstance() { return new PackedForwardBuffer(this); } } }
package org.opencloudb.parser.druid; import java.io.UnsupportedEncodingException; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.opencloudb.config.model.SystemConfig; import org.opencloudb.sequence.handler.IncrSequenceTimeHandler; import org.opencloudb.sequence.handler.IncrSequenceMySQLHandler; import org.opencloudb.sequence.handler.IncrSequencePropHandler; import org.opencloudb.sequence.handler.SequenceHandler; import org.opencloudb.util.StringUtil; /** * DruidSequence * @author * @date 2015/03/13 */ public class DruidSequenceHandler { private final SequenceHandler sequenceHandler; /** MYCAT SEQ */ private final static String MATCHED_FEATURE = "NEXT VALUE FOR MYCATSEQ_"; public DruidSequenceHandler(int seqHandlerType) { switch(seqHandlerType){ case SystemConfig.SEQUENCEHANDLER_MYSQLDB: sequenceHandler = IncrSequenceMySQLHandler.getInstance(); break; case SystemConfig.SEQUENCEHANDLER_LOCALFILE: sequenceHandler = IncrSequencePropHandler.getInstance(); break; case SystemConfig.SEQUENCEHANDLER_LOCAL_TIME: sequenceHandler = IncrSequenceTimeHandler.getInstance(); break; default: throw new java.lang.IllegalArgumentException("Invalid sequnce handler type "+seqHandlerType); } } /** * sqlsql * @param sql * @return * @throws UnsupportedEncodingException */ public String getExecuteSql(String sql,String charset) throws UnsupportedEncodingException{ String executeSql = null; if (null!=sql && !"".equals(sql)) { //sqlsqlinsertvalues String p="(?:(\\s*next\\s+value\\s+for\\s*MYCATSEQ_(\\w+))(,|\\)|\\s)*)+"; Pattern pattern = Pattern.compile(p,Pattern.CASE_INSENSITIVE); Matcher matcher = pattern.matcher(sql); if(matcher.find()) { String tableName = matcher.group(2); long value = sequenceHandler.nextId(tableName.toUpperCase()); // MATCHED_FEATURE+ executeSql = sql.replace(matcher.group(1), " "+value); } } return executeSql; } //just for test public String getTableName(String sql) { String p="(?:(\\s*next\\s+value\\s+for\\s*MYCATSEQ_(\\w+))(,|\\)|\\s)*)+"; Pattern pattern = Pattern.compile(p, Pattern.CASE_INSENSITIVE); Matcher matcher = pattern.matcher(sql); if(matcher.find()) { return matcher.group(2); } return null; } }
package org.purl.wf4ever.robundle.manifest; import static org.purl.wf4ever.robundle.utils.PathHelper.relativizeFromBase; import static org.purl.wf4ever.robundle.utils.RDFUtils.literalAsFileTime; import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.net.URISyntaxException; import java.nio.file.Path; import java.util.ArrayList; import java.util.LinkedHashSet; import java.util.List; import java.util.Set; import java.util.UUID; import java.util.logging.Logger; import org.apache.jena.riot.RDFDataMgr; import org.apache.jena.riot.RiotException; import com.github.jsonldjava.jena.JenaJSONLD; import com.hp.hpl.jena.ontology.DatatypeProperty; import com.hp.hpl.jena.ontology.Individual; import com.hp.hpl.jena.ontology.ObjectProperty; import com.hp.hpl.jena.ontology.OntClass; import com.hp.hpl.jena.ontology.OntModel; import com.hp.hpl.jena.ontology.OntModelSpec; import com.hp.hpl.jena.ontology.OntResource; import com.hp.hpl.jena.rdf.model.Model; import com.hp.hpl.jena.rdf.model.ModelFactory; import com.hp.hpl.jena.rdf.model.NodeIterator; import com.hp.hpl.jena.rdf.model.RDFNode; import com.hp.hpl.jena.rdf.model.ResIterator; import com.hp.hpl.jena.rdf.model.Resource; import com.hp.hpl.jena.rdf.model.Statement; import com.hp.hpl.jena.util.iterator.ExtendedIterator; public class RDFToManifest { private static Logger logger = Logger.getLogger(RDFToManifest.class .getCanonicalName()); static { setCachedHttpClientInJsonLD(); } private static final String PROV = "http://www.w3.org/ns/prov private static final String PROV_O = "http://www.w3.org/ns/prov-o private static final String FOAF_0_1 = "http://xmlns.com/foaf/0.1/"; private static final String PAV = "http://purl.org/pav/"; private static final String DCT = "http://purl.org/dc/terms/"; private static final String RO = "http://purl.org/wf4ever/ro private static final String BUNDLE = "http://purl.org/wf4ever/bundle private static final String ORE = "http: private static final String OA = "http://www.w3.org/ns/oa private static final String OA_RDF = "/ontologies/oa.rdf"; private static final String FOAF_RDF = "/ontologies/foaf.rdf"; private static final String BUNDLE_RDF = "/ontologies/bundle.owl"; private static final String PAV_RDF = "/ontologies/pav.rdf"; private static final String PROV_O_RDF = "/ontologies/prov-o.rdf"; private static final String PROV_AQ_RDF = "/ontologies/prov-aq.rdf"; private OntModel ore; private ObjectProperty aggregates; private ObjectProperty proxyFor; private ObjectProperty proxyIn; private OntClass aggregation; private OntModel foaf; private DatatypeProperty foafName; private OntModel pav; private ObjectProperty createdBy; private OntModel prov; private OntModel provaq; private ObjectProperty hasProvenance; private OntModel dct; private ObjectProperty conformsTo; private OntClass standard; private ObjectProperty authoredBy; private DatatypeProperty createdOn; private DatatypeProperty authoredOn; private DatatypeProperty format; private OntModel oa; private ObjectProperty hasBody; private ObjectProperty hasTarget; private ObjectProperty isDescribedBy; private OntModel bundle; private ObjectProperty hasProxy; private ObjectProperty inFolder; private ObjectProperty hasAnnotation; public RDFToManifest() { loadOntologies(); } protected void loadOntologies() { loadDCT(); loadORE(); loadFOAF(); loadPROVO(); loadPAV(); loadPROVAQ(); loadOA(); loadBundle(); } protected OntModel loadOntologyFromClasspath(String classPathUri, String uri) { OntModel ontModel = ModelFactory.createOntologyModel(); // Load from classpath InputStream inStream = getClass().getResourceAsStream(classPathUri); if (inStream == null) { throw new IllegalArgumentException("Can't load " + classPathUri); } // Ontology ontology = ontModel.createOntology(uri); ontModel.read(inStream, uri); return ontModel; } protected static Model jsonLdAsJenaModel(InputStream jsonIn, URI base) throws IOException, RiotException { JenaJSONLD.init(); Model model = ModelFactory.createDefaultModel(); RDFDataMgr.read(model, jsonIn, base.toASCIIString(), JenaJSONLD.JSONLD); return model; // Object input = JSONUtils.fromInputStream(jsonIn); // JSONLDTripleCallback callback = new JenaTripleCallback(); // Model model = (Model)JSONLD.toRDF(input, callback, new // Options(base.toASCIIString())); // return model; } /** * Use a JarCacheStorage so that our JSON-LD @context can be loaded from our * classpath and not require network connectivity * */ protected static void setCachedHttpClientInJsonLD() { // JarCacheStorage cacheStorage = new JarCacheStorage( // RDFToManifest.class.getClassLoader()); // synchronized (DocumentLoader.class) { // HttpClient oldHttpClient = DocumentLoader.getHttpClient(); // CachingHttpClient wrappedHttpClient = new CachingHttpClient( // oldHttpClient, cacheStorage, cacheStorage.getCacheConfig()); // DocumentLoader.setHttpClient(wrappedHttpClient); // synchronized (JSONUtils.class) { // HttpClient oldHttpClient = JSONUtilsSub.getHttpClient(); // CachingHttpClient wrappedHttpClient = new CachingHttpClient( // oldHttpClient, cacheStorage, cacheStorage.getCacheConfig()); // JSONUtilsSub.setHttpClient(wrappedHttpClient); } private void checkNotNull(Object... possiblyNulls) { int i = 0; for (Object check : possiblyNulls) { if (check == null) { throw new IllegalStateException("Could not load item } i++; } } protected OntModel getOntModel() { OntModel ontModel = ModelFactory .createOntologyModel(OntModelSpec.OWL_DL_MEM_RULE_INF); ontModel.setNsPrefix("foaf", FOAF_0_1); ontModel.setNsPrefix("prov", PROV); ontModel.setNsPrefix("ore", ORE); ontModel.setNsPrefix("pav", PAV); ontModel.setNsPrefix("dct", DCT); // ontModel.getDocumentManager().loadImports(foaf.getOntModel()); return ontModel; } protected synchronized void loadFOAF() { if (foaf != null) { return; } OntModel ontModel = loadOntologyFromClasspath(FOAF_RDF, FOAF_0_1); // properties from foaf foafName = ontModel.getDatatypeProperty(FOAF_0_1 + "name"); checkNotNull(foafName); foaf = ontModel; } protected synchronized void loadPAV() { if (pav != null) { return; } OntModel ontModel = loadOntologyFromClasspath(PAV_RDF, PAV); // properties from foaf createdBy = ontModel.getObjectProperty(PAV + "createdBy"); createdOn = ontModel.getDatatypeProperty(PAV + "createdOn"); authoredBy = ontModel.getObjectProperty(PAV + "authoredBy"); authoredOn = ontModel.getDatatypeProperty(PAV + "authoredOn"); checkNotNull(createdBy, createdOn, authoredBy, authoredOn); pav = ontModel; } protected synchronized void loadPROVO() { if (prov != null) { return; } OntModel ontModel = loadOntologyFromClasspath(PROV_O_RDF, PROV_O); checkNotNull(ontModel); prov = ontModel; } protected synchronized void loadPROVAQ() { if (provaq != null) { return; } OntModel ontModel = loadOntologyFromClasspath(PROV_AQ_RDF, PAV); // properties from foaf hasProvenance = ontModel.getObjectProperty(PROV + "has_provenance"); checkNotNull(hasProvenance); provaq = ontModel; } protected synchronized void loadDCT() { if (dct != null) { return; } OntModel ontModel = loadOntologyFromClasspath( "/ontologies/dcterms_od.owl", "http://purl.org/wf4ever/dcterms_od"); // properties from dct standard = ontModel.getOntClass(DCT + "Standard"); conformsTo = ontModel.getObjectProperty(DCT + "conformsTo"); // We'll cheat dc:format in format = ontModel .createDatatypeProperty("http://purl.org/dc/elements/1.1/" + "format"); checkNotNull(standard, conformsTo, format); dct = ontModel; } protected synchronized void loadOA() { if (oa != null) { return; } OntModel ontModel = loadOntologyFromClasspath(OA_RDF, OA); hasTarget = ontModel.getObjectProperty(OA + "hasTarget"); hasBody = ontModel.getObjectProperty(OA + "hasBody"); checkNotNull(hasTarget, hasBody); oa = ontModel; } protected synchronized void loadBundle() { if (bundle != null) { return; } OntModel ontModel = loadOntologyFromClasspath(BUNDLE_RDF, BUNDLE); hasProxy = ontModel.getObjectProperty(BUNDLE + "hasProxy"); hasAnnotation = ontModel.getObjectProperty(BUNDLE + "hasAnnotation"); inFolder = ontModel.getObjectProperty(BUNDLE + "inFolder"); checkNotNull(hasProxy, hasAnnotation, inFolder); bundle = ontModel; } protected synchronized void loadORE() { if (ore != null) { return; } OntModel ontModel = loadOntologyFromClasspath( "/ontologies/ore-owl.owl", "http://purl.org/wf4ever/ore-owl"); aggregation = ontModel.getOntClass(ORE + "Aggregation"); aggregates = ontModel.getObjectProperty(ORE + "aggregates"); proxyFor = ontModel.getObjectProperty(ORE + "proxyFor"); proxyIn = ontModel.getObjectProperty(ORE + "proxyIn"); isDescribedBy = ontModel.getObjectProperty(ORE + "isDescribedBy"); checkNotNull(aggregation, aggregates, proxyFor, proxyIn, isDescribedBy); ore = ontModel; } public static <T> ClosableIterable<T> iterate(ExtendedIterator<T> iterator) { return new ClosableIterable<T>(iterator); } public static class ClosableIterable<T> implements AutoCloseable, Iterable<T> { private ExtendedIterator<T> iterator; public ClosableIterable(ExtendedIterator<T> iterator) { this.iterator = iterator; } @Override public void close() { iterator.close(); } @Override public ExtendedIterator<T> iterator() { return iterator; } } public void readTo(InputStream manifestResourceAsStream, Manifest manifest, URI manifestResourceBaseURI) throws IOException, RiotException { OntModel model = new RDFToManifest().getOntModel(); model.add(jsonLdAsJenaModel(manifestResourceAsStream, manifestResourceBaseURI)); model.write(System.out, "TURTLE"); URI root = manifestResourceBaseURI.resolve("/"); Individual ro = findRO(model, root); if (ro == null) { throw new IOException("root ResearchObject not found - Not a valid RO Bundle manifest"); } for (Individual manifestResource : listObjectProperties(ro, isDescribedBy)) { String uriStr = manifestResource.getURI(); if (uriStr == null) { logger.warning("Skipping manifest without URI: " + manifestResource); continue; } // URI relative = relativizeFromBase(uriStr, root); Path path = manifest.getBundle().getFileSystem().provider() .getPath(URI.create(uriStr)); manifest.getManifest().add(path); } List<Agent> creators = getAgents(root, ro, createdBy); if (!creators.isEmpty()) { manifest.setCreatedBy(creators.get(0)); if (creators.size() > 1) { logger.warning("Ignoring additional createdBy agents"); } } RDFNode created = ro.getPropertyValue(createdOn); manifest.setCreatedOn(literalAsFileTime(created)); List<Agent> authors = getAgents(root, ro, authoredBy); if (!authors.isEmpty()) { manifest.setAuthoredBy(authors); } RDFNode authored = ro.getPropertyValue(authoredOn); manifest.setAuthoredOn(literalAsFileTime(authored)); for (Individual aggrResource : listObjectProperties(ro, aggregates)) { String uriStr = aggrResource.getURI(); // PathMetadata meta = new PathMetadata(); if (uriStr == null) { logger.warning("Skipping aggregation without URI: " + aggrResource); continue; } PathMetadata meta = manifest.getAggregation(relativizeFromBase( uriStr, root)); Set<Individual> proxies = listObjectProperties(aggrResource, hasProxy); if (! proxies.isEmpty()) { // We can only deal with the first one Individual proxy = proxies.iterator().next(); String proxyUri = null; if (proxy.getURI() != null) { proxyUri = proxy.getURI(); } else if (proxy.getSameAs() != null) { proxyUri = proxy.getSameAs().getURI(); } if (proxyUri != null) { meta.setProxy(relativizeFromBase(proxyUri, root)); } } creators = getAgents(root, aggrResource, createdBy); if (!creators.isEmpty()) { meta.setCreatedBy(creators.get(0)); if (creators.size() > 1) { logger.warning("Ignoring additional createdBy agents for " + meta); } } meta.setCreatedOn(literalAsFileTime(aggrResource .getPropertyValue(createdOn))); for (Individual standard : listObjectProperties(aggrResource, conformsTo)) { if (standard.getURI() != null) { meta.setConformsTo(relativizeFromBase(standard.getURI(), root)); } } RDFNode mediaType = aggrResource.getPropertyValue(format); if (mediaType != null && mediaType.isLiteral()) { meta.setMediatype(mediaType.asLiteral().getLexicalForm()); } } for (Individual ann : listObjectProperties(ro, hasAnnotation)) { // Normally just one body per annotation, but just in case we'll // iterate and split them out (as our PathAnnotation can // only keep a single setContent() at a time) for (Individual body : listObjectProperties( model.getOntResource(ann), hasBody)) { PathAnnotation pathAnn = new PathAnnotation(); if (body.getURI() != null) { pathAnn.setContent(relativizeFromBase(body.getURI(), root)); } else { logger.warning("Can't find annotation body for anonymous " + body); } if (ann.getURI() != null) { pathAnn.setUri(relativizeFromBase(ann.getURI(), root)); } else if (ann.getSameAs() != null && ann.getSameAs().getURI() != null) { pathAnn.setUri(relativizeFromBase(ann.getSameAs() .getURI(), root)); } // Handle multiple about/hasTarget for (Individual target : listObjectProperties(ann, hasTarget)) { if (target.getURI() != null) { pathAnn.getAboutList().add( relativizeFromBase(target.getURI(), root)); } } manifest.getAnnotations().add(pathAnn); } } } private List<Agent> getAgents(URI base, Individual in, ObjectProperty property) { List<Agent> creators = new ArrayList<>(); for (Individual agent : listObjectProperties(in, property)) { Agent a = new Agent(); if (agent.getURI() != null) { a.setUri(relativizeFromBase(agent.getURI(), base)); } RDFNode name = agent.getPropertyValue(foafName); if (name != null && name.isLiteral()) { a.setName(name.asLiteral().getLexicalForm()); } creators.add(a); } return creators; } protected static URI makeBaseURI() throws URISyntaxException { return new URI("app", UUID.randomUUID().toString(), "/", (String) null); } private Set<Individual> listObjectProperties(OntResource ontResource, ObjectProperty prop) { LinkedHashSet<Individual> results = new LinkedHashSet<>(); try (ClosableIterable<RDFNode> props = iterate(ontResource .listPropertyValues(prop))) { for (RDFNode node : props) { if (!node.isResource() || !node.canAs(Individual.class)) { continue; } results.add(node.as(Individual.class)); } } return results; } private Individual findRO(OntModel model, URI base) { try (ClosableIterable<? extends OntResource> instances = iterate(aggregation .listInstances())) { for (OntResource o : instances) { // System.out.println("Woo " + o); return o.asIndividual(); } } // Fallback - resolve as "/" // TODO: Ensure it's an Aggregation? return model.getIndividual(base.toString()); } }
package org.vetmeduni.utils.fastq; import htsjdk.samtools.SAMRecord; import htsjdk.samtools.fastq.FastqRecord; import htsjdk.samtools.util.FastqQualityFormat; import org.vetmeduni.io.FastqPairedRecord; import org.vetmeduni.utils.record.SAMRecordUtils; import java.util.concurrent.atomic.AtomicInteger; public class StandardizerAndChecker { // each 1000 reads the quality will be checked protected static final int frequency = 1000; // The encoding for this checker private final FastqQualityFormat encoding; // the number of records that passed by this count protected AtomicInteger count = new AtomicInteger(); /** * Default constructor * * @param encoding the encoding associated with the detector */ public StandardizerAndChecker(final FastqQualityFormat encoding) { this.encoding = encoding; } /** * Get the encoding for the checker * * @return the underlying encoding */ public FastqQualityFormat getEncoding() { return encoding; } /** * If by sampling is time to check, check the quality of the record. Null records are ignored * * @param record the record to check * * @throws org.vetmeduni.utils.fastq.QualityUtils.QualityException if the quality is checked and misencoded */ public void checkMisencoded(FastqRecord record) { if (record != null && count.incrementAndGet() >= frequency) { count.set(0); checkMisencoded((Object) record); } } /** * If by sampling is time to check, check the quality of the record. Null records are ignored * * @param record the record to check * * @throws org.vetmeduni.utils.fastq.QualityUtils.QualityException if the quality is checked and misencoded */ public void checkMisencoded(FastqPairedRecord record) { if (record != null && count.incrementAndGet() >= frequency) { count.set(0); checkMisencoded((Object) record.getRecord1()); checkMisencoded((Object) record.getRecord2()); } } /** * If by sampling is time to check, check the quality of the record. Null records are ignored * * @param record the record to check * * @throws org.vetmeduni.utils.fastq.QualityUtils.QualityException if the quality is checked and misencoded */ public void checkMisencoded(SAMRecord record) { if (record != null && count.incrementAndGet() >= frequency) { count.set(0); checkMisencoded((Object) record); } } /** * Check an object (instance of SAMRecord, FastqRecord or FastqPairedRecord) * * @param record the record to check */ protected void checkMisencoded(Object record) { final byte[] quals; if (record instanceof SAMRecord) { quals = ((SAMRecord) record).getBaseQualityString().getBytes(); } else if (record instanceof FastqRecord) { quals = ((FastqRecord) record).getBaseQualityString().getBytes(); } else { throw new IllegalArgumentException("checkMisencoded only accepts FastqRecord/SAMRecord"); } QualityUtils.checkEncoding(quals, encoding); } /** * Standardize a record, checking at the same time the quality * * @param record the record to standardize * * @return a new record with the standard encoding or the same if the encoder is sanger; <code>null</code> if the * argument is null * @throws org.vetmeduni.utils.fastq.QualityUtils.QualityException if the conversion causes a misencoded quality */ public FastqRecord standardize(FastqRecord record) { if (record == null) { return record; } if (QualityUtils.isStandard(encoding)) { checkMisencoded(record); return record; } byte[] asciiQualities = record.getBaseQualityString().getBytes(); byte[] newQualities = new byte[asciiQualities.length]; for (int i = 0; i < asciiQualities.length; i++) { newQualities[i] = QualityUtils.byteToSanger(asciiQualities[i]); QualityUtils.checkStandardEncoding(newQualities[i]); } return new FastqRecord(record.getReadHeader(), record.getReadString(), record.getBaseQualityHeader(), new String(newQualities)); } /** * Standardize a record, checking at the same time the quality * * @param record the record to standardize * * @return a new record with the standard encoding or the same if the encoder is sanger; <code>null</code> if the * argument is null * @throws org.vetmeduni.utils.fastq.QualityUtils.QualityException if the conversion causes a misencoded quality */ public FastqPairedRecord standardize(FastqPairedRecord record) { if (record == null) { return record; } FastqRecord record1 = standardize(record.getRecord1()); FastqRecord record2 = standardize(record.getRecord2()); return new FastqPairedRecord(record1, record2); } /** * Standardize a record, checking at the same time the quality * * @param record the record to standardize * * @return a new record with the standard encoding or the same if the encoder is sanger; <code>null</code> if the * argument is null * @throws org.vetmeduni.utils.fastq.QualityUtils.QualityException if the conversion causes a misencoded quality */ public SAMRecord standardize(SAMRecord record) { if (record == null) { return record; } if (QualityUtils.isStandard(encoding)) { checkMisencoded(record); return record; } try { SAMRecord newRecord = (SAMRecord) record.clone(); // relies on the checking of the record SAMRecordUtils.toSanger(newRecord); return newRecord; } catch (CloneNotSupportedException e) { // This should not happen, because it is suppose to be implemented throw new RuntimeException("Unreachable code: " + e.getMessage()); } } }
package ru.colibri.ui.settings.loaders; import lombok.extern.java.Log; import org.apache.commons.lang3.StringUtils; import org.springframework.beans.factory.InitializingBean; import ru.colibri.ui.core.exception.PropertyNotFoundException; import ru.colibri.ui.core.settings.TestSettings; import ru.colibri.ui.settings.general.PropertyUtils; import java.io.File; import java.io.IOException; import java.net.URL; import java.util.Arrays; import java.util.List; import java.util.Map; import java.util.Properties; import java.util.logging.Level; import java.util.stream.Collectors; import static java.lang.String.format; import static org.apache.commons.io.FileUtils.copyURLToFile; @Log public abstract class AbsSettingsLoader implements ISettingsLoader, InitializingBean { protected static final String PATH_TEMPLATE = "src/test/resources/environment/%s/device.properties"; protected static final String PATH_USER = "src/test/resources/users/%s.properties"; private static final String TEST_TYPE_FILTER = "src/test/resources/planTestCycle/testCycle.properties"; protected Map<String, String> convertPropertyToMap(Properties properties) { return properties.entrySet().stream().collect( Collectors.toMap( e -> e.getKey().toString(), e -> e.getValue().toString() ) ); } protected void takeArtifact(String from, String to) { try { log.log(Level.INFO, format("Loading artifact from: %s", from)); copyURLToFile(new URL(from), new File(to)); log.log(Level.INFO, format("Loading artifact complete to: %s", to)); } catch (IOException e) { log.log(Level.WARNING, "Error loading file.", e); } } @Override public TestSettings loadTestSettings(String testType) { if (StringUtils.isEmpty(testType)) throw new IllegalArgumentException("Не задан тестовый цикл, проверьте данные"); List<String> testCycleFilters = getTestCycleFilters(testType); return TestSettings.builder() .flagsMetaFilters(testCycleFilters) .build(); } private List<String> getTestCycleFilters(String testType) { if (testType.matches(".*?[+-].*?")) { return getFreeTypeTestCycleFilters(testType); } else { return getTestCycleFiltersFromProperty(testType); } } private List<String> getTestCycleFiltersFromProperty(String testType) { Properties props = PropertyUtils.readProperty(TEST_TYPE_FILTER); String testCycle = props.getProperty(testType); if (StringUtils.isEmpty(testCycle)) { throw new PropertyNotFoundException(testType, TEST_TYPE_FILTER); } return getFreeTypeTestCycleFilters(testCycle); } private List<String> getFreeTypeTestCycleFilters(String testCycle) { List<String> testCycleFilters = Arrays.stream(testCycle.split(",")).collect(Collectors.toList()); checkTestCycleFiltersSyntax(testCycleFilters); return testCycleFilters; } private void checkTestCycleFiltersSyntax(List<String> testCycleFilters) { boolean correctFiltersSyntax = testCycleFilters.stream() .allMatch(filter -> filter.matches("^[+-]\\w*")); if (!correctFiltersSyntax) { throw new IllegalArgumentException("Неправильный синтаксис фильтров тестового цикла, проверьте данные"); } } @Override public void afterPropertiesSet() throws Exception { log.info(format("Bean %s loaded", this.getClass().getSimpleName())); } }
package se.kth.rest.application.config; import java.util.Set; import javax.ws.rs.core.Application; import org.glassfish.jersey.media.multipart.MultiPartFeature; /** * * @author Ermias */ @javax.ws.rs.ApplicationPath("api") public class ApplicationConfig extends Application { @Override public Set<Class<?>> getClasses() { Set<Class<?>> resources = new java.util.HashSet<>(); resources.add(MultiPartFeature.class); addRestResourceClasses(resources); return resources; } /** * Do not modify addRestResourceClasses() method. * It is automatically populated with * all resources defined in the project. * If required, comment out calling this method in getClasses(). */ private void addRestResourceClasses(Set<Class<?>> resources) { resources.add(se.kth.hopsworks.filters.RequestAuthFilter.class); resources.add(se.kth.hopsworks.rest.ActivityService.class); resources.add(se.kth.hopsworks.rest.AppExceptionMapper.class); resources.add(se.kth.hopsworks.rest.AuthExceptionMapper.class); resources.add(se.kth.hopsworks.rest.AuthService.class); resources.add(se.kth.hopsworks.rest.CuneiformService.class); resources.add(se.kth.hopsworks.rest.DataSetService.class); resources.add(se.kth.hopsworks.rest.ProjectMembers.class); resources.add(se.kth.hopsworks.rest.ProjectService.class); resources.add(se.kth.hopsworks.rest.ThrowableExceptionMapper.class); resources.add(se.kth.hopsworks.rest.TransactionExceptionMapper.class); resources.add(se.kth.hopsworks.rest.UserService.class); } }
package vg.civcraft.mc.citadel.listener; import java.util.Collection; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.UUID; import org.bukkit.Bukkit; import org.bukkit.Location; import org.bukkit.Material; import org.bukkit.Tag; import org.bukkit.block.Block; import org.bukkit.block.BlockFace; import org.bukkit.block.data.Bisected; import org.bukkit.block.data.BlockData; import org.bukkit.block.data.Openable; import org.bukkit.block.data.type.Door; import org.bukkit.block.data.type.Switch; import org.bukkit.entity.Entity; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.Listener; import org.bukkit.event.block.Action; import org.bukkit.event.block.BlockPistonExtendEvent; import org.bukkit.event.block.BlockPistonRetractEvent; import org.bukkit.event.block.BlockRedstoneEvent; import org.bukkit.event.player.PlayerInteractEvent; import vg.civcraft.mc.citadel.Citadel; import vg.civcraft.mc.citadel.CitadelPermissionHandler; import vg.civcraft.mc.citadel.ReinforcementLogic; import vg.civcraft.mc.citadel.model.Reinforcement; import vg.civcraft.mc.civmodcore.api.BlockAPI; public class RedstoneListener implements Listener { private static boolean isAuthorizedPlayerNear(Reinforcement reinforcement, double distance) { Location reinLocation = reinforcement.getLocation(); if (reinLocation.getWorld() == null) { return false; } // distance is radius, not diameter double diameter = distance * 2; Collection<Entity> entities = reinLocation.getWorld().getNearbyEntities(reinLocation, diameter, diameter, diameter, e -> e instanceof Player && !e.isDead() && reinforcement.hasPermission(e.getUniqueId(), CitadelPermissionHandler.getDoors()) && e.getLocation().distanceSquared(reinLocation) <= diameter * diameter); return !entities.isEmpty(); } private double maxRedstoneDistance; private Map<Location, List<UUID>> authorizations; public RedstoneListener(double maxRedstoneDistance) { this.maxRedstoneDistance = maxRedstoneDistance; this.authorizations = new HashMap<>(); Bukkit.getScheduler().scheduleSyncRepeatingTask(Citadel.getInstance(), () -> authorizations.clear(), 1, 1); } @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) public void pistonExtend(BlockPistonExtendEvent bpee) { for (Block block : bpee.getBlocks()) { Reinforcement reinforcement = ReinforcementLogic.getReinforcementProtecting(block); if (reinforcement != null) { bpee.setCancelled(true); break; } } } @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) public void pistonRetract(BlockPistonRetractEvent bpre) { for (Block block : bpre.getBlocks()) { Reinforcement reinforcement = ReinforcementLogic.getReinforcementProtecting(block); if (reinforcement != null) { bpre.setCancelled(true); break; } } } @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) public void pressButton(PlayerInteractEvent e) { if (e.getAction() != Action.RIGHT_CLICK_BLOCK) { return; } if (!(e.getClickedBlock().getBlockData() instanceof Switch)) { return; } Switch button = (Switch) (e.getClickedBlock().getBlockData()); Block buttonBlock = e.getClickedBlock(); Block attachedBlock = e.getClickedBlock().getRelative(button.getFacing().getOppositeFace()); // prepare all sides of button itself setupAdjacentDoors(e.getPlayer(), buttonBlock, button.getFacing().getOppositeFace()); // prepare all sides of the block attached to setupAdjacentDoors(e.getPlayer(), attachedBlock, button.getFacing()); } @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) public void redstonePower(BlockRedstoneEvent bre) { // prevent doors from being opened by redstone if (bre.getNewCurrent() <= 0 || bre.getOldCurrent() > 0) { return; } Block block = bre.getBlock(); BlockData blockData = block.getBlockData(); if (!(blockData instanceof Openable)) { return; } Openable openable = (Openable) blockData; if (openable.isOpen()) { return; } if (blockData instanceof Door) { //we always store the activation for the lower half of a door Door door = (Door) blockData; if (door.getHalf() == Bisected.Half.TOP) { block = block.getRelative(BlockFace.DOWN); } } Reinforcement rein = ReinforcementLogic.getReinforcementProtecting(block); if (rein == null) { return; } if (rein.isInsecure()) { boolean playerNearby = isAuthorizedPlayerNear(rein, maxRedstoneDistance); if (!playerNearby) { bre.setNewCurrent(bre.getOldCurrent()); } return; } List<UUID> playersActivating = authorizations.get(block.getLocation()); if (playersActivating == null) { bre.setNewCurrent(bre.getOldCurrent()); return; } for (UUID uuid : playersActivating) { if (rein.hasPermission(uuid, CitadelPermissionHandler.getDoors())) { // single valid perm is enough to open return; } } // noone valid found nearby, so deny bre.setNewCurrent(bre.getOldCurrent()); } private void setupAdjacentDoors(Player player, Block block, BlockFace skip) { for (Entry<BlockFace,Block> entry : BlockAPI.getAllSidesMapped(block).entrySet()) { if (entry.getKey() == skip) { continue; } Block rel = entry.getValue(); BlockData blockData = rel.getBlockData(); if (!(blockData instanceof Openable)) { continue; } Location locationToSave; if (blockData instanceof Door) { Door door = (Door) blockData; if (door.getHalf() == Bisected.Half.TOP) { // block is upper half of a door locationToSave = rel.getRelative(BlockFace.DOWN).getLocation(); } else { // already the lower half of the door locationToSave = rel.getLocation(); } } else { locationToSave = rel.getLocation(); } List<UUID> existingAuths = authorizations.computeIfAbsent(locationToSave, k -> new LinkedList<>()); existingAuths.add(player.getUniqueId()); } } @EventHandler(priority = EventPriority.LOW, ignoreCancelled = true) public void stepPressurePlate(PlayerInteractEvent e) { if (e.getAction() != Action.PHYSICAL) { return; } Material mat = e.getClickedBlock().getType(); if (mat != Material.STONE_PRESSURE_PLATE && mat != Material.LIGHT_WEIGHTED_PRESSURE_PLATE && mat != Material.HEAVY_WEIGHTED_PRESSURE_PLATE && !Tag.WOODEN_PRESSURE_PLATES.isTagged(mat)) { return; } setupAdjacentDoors(e.getPlayer(), e.getClickedBlock(), BlockFace.EAST_SOUTH_EAST); } }
package net.java.sip.communicator.impl.credentialsstorage; import java.security.*; import java.security.spec.*; import javax.crypto.*; import javax.crypto.spec.*; import net.java.sip.communicator.service.credentialsstorage.*; import net.java.sip.communicator.util.*; /** * Performs encryption and decryption of text using AES algorithm. * * @author Dmitri Melnikov */ public class AESCrypto implements Crypto { /** * The algorithm associated with the key. */ private static final String KEY_ALGORITHM = "AES"; /** * AES in ECB mode with padding. */ private static final String CIPHER_ALGORITHM = "AES/ECB/PKCS5PADDING"; /** * Salt used when creating the key. */ private static byte[] SALT = { 0x0C, 0x0A, 0x0F, 0x0E, 0x0B, 0x0E, 0x0E, 0x0F }; /** * Possible length of the keys in bits. */ private static int[] KEY_LENGTHS = new int[]{256, 128}; /** * Number of iterations to use when creating the key. */ private static int ITERATION_COUNT = 1024; /** * Key derived from the master password to use for encryption/decryption. */ private Key key; /** * Decryption object. */ private Cipher decryptCipher; /** * Encryption object. */ private Cipher encryptCipher; /** * Creates the encryption and decryption objects and the key. * * @param masterPassword used to derive the key. Can be null. */ public AESCrypto(String masterPassword) { try { // we try init of key with suupplied lengths // we stop after the first successful attempt for (int i = 0; i < KEY_LENGTHS.length; i++) { decryptCipher = Cipher.getInstance(CIPHER_ALGORITHM); encryptCipher = Cipher.getInstance(CIPHER_ALGORITHM); try { initKey(masterPassword, KEY_LENGTHS[i]); // its ok stop trying break; } catch (InvalidKeyException e) { if(i == KEY_LENGTHS.length - 1) throw e; } } } catch (InvalidKeyException e) { throw new RuntimeException("Invalid key", e); } catch (InvalidKeySpecException e) { throw new RuntimeException("Invalid key specification", e); } catch (NoSuchAlgorithmException e) { throw new RuntimeException("Algorithm not found", e); } catch (NoSuchPaddingException e) { throw new RuntimeException("Padding not found", e); } } /** * Initialize key with specified length. * * @param masterPassword used to derive the key. Can be null. * @param keyLength Length of the key in bits. * @throws InvalidKeyException if the key is invalid (bad encoding, * wrong length, uninitialized, etc). * @throws NoSuchAlgorithmException if the algorithm chosen does not exist * @throws InvalidKeySpecException if the key specifications are invalid */ private void initKey(String masterPassword, int keyLength) throws InvalidKeyException, NoSuchAlgorithmException, InvalidKeySpecException { // if the password is empty, we get an exception constructing the key if (masterPassword == null) { // here a default password can be set, // cannot be an empty string masterPassword = " "; } // Password-Based Key Derivation Function found in PKCS5 v2.0. // This is only available with java 6. SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1"); // Make a key from the master password KeySpec spec = new PBEKeySpec(masterPassword.toCharArray(), SALT, ITERATION_COUNT, keyLength); SecretKey tmp = factory.generateSecret(spec); // Make an algorithm specific key key = new SecretKeySpec(tmp.getEncoded(), KEY_ALGORITHM); // just a check whether the key size is wrong encryptCipher.init(Cipher.ENCRYPT_MODE, key); decryptCipher.init(Cipher.DECRYPT_MODE, key); } /** * Decrypts the cyphertext using the key. * * @param ciphertext base64 encoded encrypted data * @return decrypted data * @throws CryptoException when the ciphertext cannot be decrypted with the * key or on decryption error. */ public String decrypt(String ciphertext) throws CryptoException { try { decryptCipher.init(Cipher.DECRYPT_MODE, key); return new String(decryptCipher.doFinal(Base64.decode(ciphertext)), "UTF-8"); } catch (BadPaddingException e) { throw new CryptoException(CryptoException.WRONG_KEY, e); } catch (Exception e) { throw new CryptoException(CryptoException.DECRYPTION_ERROR, e); } } /** * Encrypts the plaintext using the key. * * @param plaintext data to be encrypted * @return base64 encoded encrypted data * @throws CryptoException on encryption error */ public String encrypt(String plaintext) throws CryptoException { try { encryptCipher.init(Cipher.ENCRYPT_MODE, key); return new String(Base64.encode(encryptCipher.doFinal(plaintext .getBytes("UTF-8")))); } catch (Exception e) { throw new CryptoException(CryptoException.ENCRYPTION_ERROR, e); } } }
/* * FastImputationBitFixedWindow */ package net.maizegenetics.gbs.pipeline; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.TreeMap; import net.maizegenetics.baseplugins.ConvertSBitTBitPlugin; import net.maizegenetics.util.OpenBitSet; import net.maizegenetics.pal.alignment.Alignment; import net.maizegenetics.pal.alignment.AlignmentUtils; import net.maizegenetics.pal.alignment.ExportUtils; import net.maizegenetics.pal.alignment.ImportUtils; import net.maizegenetics.pal.alignment.MutableNucleotideAlignment; import net.maizegenetics.pal.alignment.NucleotideAlignmentConstants; import net.maizegenetics.pal.statistics.ChiSquareTest; /** * An extremely fast imputation approach that uses KNN, but calculates the matrix * with a 64 bit window, and it does all operations with bits. This has a fixed window size * unlike the other BDI imputation approaches. * * All heterozygous sets are to missing. * * Definitely a work in progress. * Perhaps we should do ratio to major/minor * Perhaps we should scan for massive nearly identical regions * Need to decide whether P or Length/Identity approach is better * * @author ed */ public class FastImputationBitFixedWindow { short[][] matchInWin, diffInWin; float[] presentProp; //Present proportion int[] presentCntForSites; int[] presentCntForTaxa; int[] hetCntForTaxa; boolean[] highHet = null; long totalPresent = 0; Alignment anchorAlignment = null; MutableNucleotideAlignment impAlign = null; static int windowSize = 64 * 64; //left and right distance of 64bp window, so window 2 is 2+1+2=5 or 320bp static int minLengthOfMatch = 50; static double minIdentity = 0.95; //std 0.99, 0.95 gave some pretty good results also static int minCountNNperLine = 4; //std 4 static int minCountNNperSite = 2; //std 2 static int segments = 1; static double majorityRule = 0.76; static double maxLineErrorRate = 0.025; //std 0.01 static boolean imputeGaps = false; static boolean maskHighHets = true; static double maxHetStatic = 0.01; //HetStat = hetSiteCnt/covSiteCnt : empirically derived // static int minimumMajorityRule=4; //NN within is used, and tie are not imputed public FastImputationBitFixedWindow(Alignment a, boolean[] highHet) { this.highHet = highHet; this.anchorAlignment = ConvertSBitTBitPlugin.convertAlignment(a, ConvertSBitTBitPlugin.CONVERT_TYPE.tbit, null); double avgMissing = calcPropMissingByLine(); System.out.println("Average Missing:" + avgMissing); avgMissing = calcPropMissing(); System.out.println("Average Missing (site and taxa):" + avgMissing + " totalPresent" + totalPresent); System.out.println("Average MAF:" + avgMinorAlleleFrequency()); reportTaxaStats(); AlignmentFilterByGBSUtils.getCoverage_MAF_F_Dist(anchorAlignment, false); double realDist = AlignmentFilterByGBSUtils.getErrorRateForDuplicatedTaxa(anchorAlignment, true, false, true); double randomDist = AlignmentFilterByGBSUtils.getErrorRateForDuplicatedTaxa(anchorAlignment, true, true, false); System.out.println("Ratio of RandomToReal:" + randomDist / realDist); System.out.println("Creating mutable alignment"); impAlign = MutableNucleotideAlignment.getInstance(a); //impAlign = new MutableSimpleAlignment(a); for (int i = 4096; i >= 1024; i /= 2) { // segments=i; System.out.println("Starting imputation"); // windowSize=((a.getSiteCount()/64)/segments)*64; windowSize = i; int offset = 0; System.out.println("Window size:" + windowSize + " offset:" + offset); imputeBySiteJump(windowSize, 0, minLengthOfMatch, minIdentity); // realDist=AlignmentFilterByGBSUtils.getErrorRateForDuplicatedTaxa(impAlign, true,false,false); // randomDist=AlignmentFilterByGBSUtils.getErrorRateForDuplicatedTaxa(impAlign, true,true,false); // System.out.println("Ratio of RandomToReal:"+randomDist/realDist); System.out.println("Window size:" + windowSize + " offset:" + offset); AlignmentFilterByGBSUtils.getCoverage_MAF_F_Dist(impAlign, false); offset = windowSize / 2; System.out.println("Window size:" + windowSize + " offset:" + offset); imputeBySiteJump(windowSize, offset, minLengthOfMatch, minIdentity); System.out.println("Window size:" + windowSize + " offset:" + offset); AlignmentFilterByGBSUtils.getCoverage_MAF_F_Dist(impAlign, false); System.out.println("Xratio: " + countXRateInImputation()); } } public FastImputationBitFixedWindow(Alignment a) { this(a, null); } private double avgMinorAlleleFrequency() { long totmj = 0, totmn = 0; for (int i = 0; i < anchorAlignment.getSequenceCount(); i++) { totmj += anchorAlignment.getAllelePresenceForAllSites(i, 0).cardinality(); totmn += anchorAlignment.getAllelePresenceForAllSites(i, 1).cardinality(); //totmj += anchorAlignment.getTaxaBitsNoClone(i, 0).cardinality(); //totmn += anchorAlignment.getTaxaBitsNoClone(i, 1).cardinality(); } double theMAF = (double) totmn / (double) (totmj + totmn); return theMAF; } private double countXRateInImputation() { long xCnt = 0, knownCnt = 0; for (int i = 0; i < impAlign.getSequenceCount(); i++) { for (int j = 0; j < impAlign.getSiteCount(); j++) { if (impAlign.getBase(i, j) != Alignment.UNKNOWN_DIPLOID_ALLELE) { knownCnt++; if (impAlign.getBase(i, j) == (byte) 'X') { xCnt++; } } } } double theXRate = (double) xCnt / (double) knownCnt; return theXRate; } public void reportTaxaStats() { double sites = anchorAlignment.getSiteCount(); for (int t = 0; t < anchorAlignment.getSequenceCount(); t++) { System.out.printf("%s %d %.5g %d %.5g %s %n", anchorAlignment.getIdGroup().getIdentifier(t).getFullName(), presentCntForTaxa[t], (double) presentCntForTaxa[t] / sites, hetCntForTaxa[t], (double) hetCntForTaxa[t] / sites, highHet[t]); } } private double calcPropMissing() { boolean calculateHighHet = false; presentCntForTaxa = new int[anchorAlignment.getSequenceCount()]; presentCntForSites = new int[anchorAlignment.getSiteCount()]; hetCntForTaxa = new int[anchorAlignment.getSequenceCount()]; if (highHet == null) { highHet = new boolean[anchorAlignment.getSequenceCount()]; calculateHighHet = true; } totalPresent = 0; double sd = anchorAlignment.getSiteCount(); for (int t = 0; t < anchorAlignment.getSequenceCount(); t++) { for (int s = 0; s < anchorAlignment.getSiteCount(); s++) { byte cb = anchorAlignment.getBase(t, s); if ((cb != Alignment.UNKNOWN_DIPLOID_ALLELE) && (cb != NucleotideAlignmentConstants.GAP_DIPLOID_ALLELE)) { presentCntForTaxa[t]++; presentCntForSites[s]++; if (AlignmentUtils.isHeterozygous(cb)) { hetCntForTaxa[t]++; } totalPresent++; } } // double covProp=(double)presentCntForTaxa[t]/sd; double hetProp = (double) hetCntForTaxa[t] / presentCntForTaxa[t]; if (calculateHighHet) { highHet[t] = (hetProp > maxHetStatic) ? true : false; } } return (double) totalPresent / ((double) anchorAlignment.getSequenceCount() * (double) anchorAlignment.getSiteCount()); } private double calcPropMissingByLine() { presentProp = new float[anchorAlignment.getSequenceCount()]; double avgMissing = 0; for (int i = 0; i < anchorAlignment.getSequenceCount(); i++) { long present = OpenBitSet.unionCount(anchorAlignment.getAllelePresenceForAllSites(i, 0), anchorAlignment.getAllelePresenceForAllSites(i, 1)); //long present = OpenBitSet.unionCount(anchorAlignment.getTaxaBitsNoClone(i, 0), anchorAlignment.getTaxaBitsNoClone(i, 1)); presentProp[i] = (float) present / (float) anchorAlignment.getSiteCount(); avgMissing += presentProp[i]; } return avgMissing / (double) anchorAlignment.getSequenceCount(); } private void imputeBySiteJump(int window, int offset, int minLength, double minIdentity) { long time = System.currentTimeMillis(); int knownSNPs = 0, unknownSNPs = 0, imputedSNPs = 0; int numSeqs = anchorAlignment.getSequenceCount(); System.out.println("Initial matrix created in " + (System.currentTimeMillis() - time)); time = System.currentTimeMillis(); int corrCnt = 0, wrongCnt = 0, gapCnt = 0; int imputableLines = 0, imputedWithHighError = 0; TreeMap<Double, Integer> lenBestLine = new TreeMap<Double, Integer>(Collections.reverseOrder()); for (int b = 0 + offset; b < anchorAlignment.getSiteCount() - window; b += window) { // currWord=b>>6; int endBase = b + window; initHapLengths(b, endBase); double rate = (double) unknownSNPs / (double) (System.currentTimeMillis() - time); System.out.println("Imputed base:" + b + " known:" + knownSNPs + " unknownSNPs:" + unknownSNPs + " imputed:" + imputedSNPs + " Rate:" + rate); for (int i = 0; i < numSeqs; i++) { if (maskHighHets && highHet[i]) { continue; } lenBestLine.clear(); for (int j = 0; j < numSeqs; j++) { if (i == j) { continue; } if (maskHighHets && highHet[j]) { continue; } int sum = matchInWin[i][j] + diffInWin[i][j]; double identity = (double) matchInWin[i][j] / (double) sum; if ((sum > minLength) && (identity > minIdentity)) { lenBestLine.put(identity, j); } } if (lenBestLine.size() < minCountNNperLine) { continue; } imputableLines++; if (i == 0) { System.out.println(" cnt" + lenBestLine.size()); } // byte[] calls=consensusCalls(anchorAlignment, i, b, endBase, lenBestLine, false, majorityRule, minCountNNperSite); // System.out.println(Arrays.toString(calls)); byte[] calls = consensusCallBit(anchorAlignment, i, b, endBase, lenBestLine, false, majorityRule, minCountNNperSite, true, imputeGaps); //determine error while ignoring known int[] callError = compareCallsWithActual(anchorAlignment, b, i, calls); double lineError = (double) callError[1] / (double) (callError[1] + callError[0]); if (lineError > maxLineErrorRate) { imputedWithHighError++; // System.out.println("high error line:"+anchorAlignment.getTaxaName(i)+" Error:"+lineError); continue; } calls = consensusCallBit(anchorAlignment, i, b, endBase, lenBestLine, false, majorityRule, minCountNNperSite, false, imputeGaps); //recall with known; currently conflict are set to unknown setBaseInImputedAlignment(impAlign, b, i, calls); // if(b>3000) System.out.println(Arrays.toString(callError)); corrCnt += callError[0]; wrongCnt += callError[1]; gapCnt += callError[3]; double errorRate = (double) wrongCnt / (double) (corrCnt + wrongCnt); if (i % 100 == 0) { System.out.printf("%d-%d %d R: %d W: %d G: %d ErrorRate: %g Imputable:%d ImputedHighError:%d %n", b, endBase, i, corrCnt, wrongCnt, gapCnt, errorRate, imputableLines, imputedWithHighError); } } double errorRate = (double) wrongCnt / (double) (corrCnt + wrongCnt); System.out.printf("R: %d W: %d ErrorRate: %g %n", corrCnt, wrongCnt, errorRate); } } private int[] compareCallsWithActual(Alignment a, int startBase, int taxon, byte[] calls) { int[] result = new int[4]; //agree[0], disagree[1], noncomparison[2], gaps[3] byte alignB; for (int s = 0; s < calls.length; s++) { alignB = a.getBase(taxon, s + startBase); if (calls[s] == NucleotideAlignmentConstants.GAP_DIPLOID_ALLELE) { result[3]++; } if (calls[s] == Alignment.UNKNOWN_DIPLOID_ALLELE) { result[2]++; } else if (alignB == Alignment.UNKNOWN_DIPLOID_ALLELE) { result[2]++; } else if (alignB == calls[s]) { result[0]++; } else { result[1]++; } } return result; } private void setBaseInImputedAlignment(MutableNucleotideAlignment a, int startBase, int taxon, byte[] calls) { for (int s = 0; s < calls.length; s++) { if (calls[s] != Alignment.UNKNOWN_DIPLOID_ALLELE) { byte cb = a.getBase(taxon, s + startBase); if (cb == Alignment.UNKNOWN_DIPLOID_ALLELE) { a.setBase(taxon, s + startBase, calls[s]); } else if (cb != calls[s]) { a.setBase(taxon, s + startBase, Alignment.UNKNOWN_DIPLOID_ALLELE); } } } } private byte[] consensusCalls(Alignment a, int taxon, int startBase, int endBase, TreeMap<Double, Integer> taxa, boolean callhets, double majority) { short[][] siteCnt = new short[2][a.getSiteCount()]; int[] taxaIndex = new int[taxa.size()]; ArrayList<Integer> taxaList = new ArrayList(taxa.values()); for (int t = 0; t < taxaIndex.length; t++) { taxaIndex[t] = taxaList.get(t); } byte[] calls = new byte[endBase - startBase]; Arrays.fill(calls, Alignment.UNKNOWN_DIPLOID_ALLELE); for (int s = startBase; s < endBase; s++) { calls[s - startBase] = a.getBase(taxon, s); byte mj = a.getMajorAllele(s); byte mn = a.getMinorAllele(s); byte het = AlignmentUtils.getDiploidValue(mj, mn); //byte[] snpValue = {mj, mn}; //byte het = IUPACNucleotides.getDegerateSNPByteFromTwoSNPs(snpValue); for (int t = 0; t < taxaIndex.length; t++) { byte ob = a.getBase(taxaIndex[t], s); if (ob == Alignment.UNKNOWN_DIPLOID_ALLELE) { continue; } if (ob == mj) { siteCnt[0][s]++; } else if (ob == mn) { siteCnt[1][s]++; } else if (ob == het) { siteCnt[0][s]++; siteCnt[1][s]++; } } int totalCnt = siteCnt[0][s] + siteCnt[1][s]; if (totalCnt == 0) { continue; //no data leave missing } if ((double) siteCnt[0][s] / (double) totalCnt > majority) { calls[s - startBase] = mj; } else if ((double) siteCnt[1][s] / (double) totalCnt > majority) { calls[s - startBase] = mn; } else if (callhets) { calls[s - startBase] = het; } } // System.out.println("Byt:"+Arrays.toString(siteCnt[0])); return calls; } private byte[] consensusCallBit(Alignment a, int taxon, int startBase, int endBase, TreeMap<Double, Integer> taxa, boolean callhets, double majority, int minCount, boolean ignoreKnownBases, boolean imputeGaps) { int[] taxaIndex = new int[taxa.size()]; ArrayList<Integer> taxaList = new ArrayList(taxa.values()); for (int t = 0; t < taxaIndex.length; t++) { taxaIndex[t] = taxaList.get(t); } short[][] siteCnt = new short[2][endBase - startBase]; double[] sumExpPresent = new double[endBase - startBase]; int[] sumNNxSitePresent = new int[endBase - startBase]; int sumNNPresent = 0; for (int t = 0; t < taxaIndex.length; t++) { sumNNPresent += presentCntForTaxa[taxaIndex[t]]; } byte[] calls = new byte[endBase - startBase]; Arrays.fill(calls, Alignment.UNKNOWN_DIPLOID_ALLELE); for (int alignS = startBase; alignS < endBase; alignS += 64) { int currWord = alignS / 64; int callSite = alignS - startBase; for (int t = 0; t < taxaIndex.length; t++) { long bmj = anchorAlignment.getAllelePresenceForAllSites(taxaIndex[t], 0).getBits()[currWord]; //long bmj = anchorAlignment.getTaxaBitsNoClone(taxaIndex[t], 0).getBits()[currWord]; long bmn = anchorAlignment.getAllelePresenceForAllSites(taxaIndex[t], 1).getBits()[currWord]; //long bmn = anchorAlignment.getTaxaBitsNoClone(taxaIndex[t], 1).getBits()[currWord]; int cs = callSite; for (int j = 0; j < 64; j++) { boolean presentFlag = false; if ((bmj & 0x01) != 0) { siteCnt[0][cs]++; presentFlag = true; } bmj = bmj >> 1; if ((bmn & 0x01) != 0) { siteCnt[1][cs]++; presentFlag = true; } bmn = bmn >> 1; sumExpPresent[cs] += presentProp[taxaIndex[t]]; if (presentFlag) { sumNNxSitePresent[cs]++; } cs++; } } } // System.out.println("Bit:"+Arrays.toString(siteCnt[0])); for (int alignS = startBase; alignS < endBase; alignS++) { int callS = alignS - startBase; byte ob = a.getBase(taxon, alignS); if (ignoreKnownBases) { ob = Alignment.UNKNOWN_DIPLOID_ALLELE; } calls[callS] = ob; byte mj = a.getMajorAllele(alignS); byte mn = a.getMinorAllele(alignS); int totalCnt = siteCnt[0][callS] + siteCnt[1][callS]; // double expPres=sumExpPresent[callS]/(double)taxaIndex.length; // System.out.println(Arrays.toString(exp)+Arrays.toString(obs)); if (imputeGaps && ((double) totalCnt < ((double) sumExpPresent[callS] / 2.0))) { // double[] exp= {expPres,1-expPres}; // int[] obs={totalCnt,taxaIndex.length-totalCnt}; int nonNNPresentCnt = (int) totalPresent - sumNNPresent; //marginals int nonSitePresentCnt = (int) totalPresent - presentCntForSites[callS]; //marginals int[] obs2 = {sumNNxSitePresent[callS], presentCntForSites[callS] - sumNNxSitePresent[callS], sumNNPresent - sumNNxSitePresent[callS], (int) totalPresent - presentCntForSites[callS] - sumNNPresent + sumNNxSitePresent[callS]}; double totalPresentSqr = (double) totalPresent * (double) totalPresent; double[] exp2 = {(double) sumNNPresent * (double) presentCntForSites[callS] / totalPresentSqr, (double) nonNNPresentCnt * (double) presentCntForSites[callS] / totalPresentSqr, (double) sumNNPresent * (double) nonSitePresentCnt / totalPresentSqr, (double) nonNNPresentCnt * (double) nonSitePresentCnt / totalPresentSqr}; // double presProbX2=ChiSquareTest.compare(exp, obs); double presProbX2v2 = ChiSquareTest.compare(exp2, obs2); // System.out.printf("%d %d %d %d %g %g %n",taxaIndex.length, siteCnt[0][callS],siteCnt[1][callS],totalCnt, // sumExpPresent[callS], presProbX2); // System.out.println(Arrays.toString(obs2)+Arrays.toString(exp2)+" P:"+presProbX2v2); // System.out.printf("%d %d %d %d %g %g %n",taxaIndex.length, siteCnt[0][callS],siteCnt[1][callS],totalCnt, // sumExpPresent[callS], presProbX2); // if((presProbX2>=0)&&(presProbX2<0.01)) {calls[callS]=NucleotideAlignmentConstants.GAP_DIPLOID_ALLELE; continue;} if ((presProbX2v2 >= 0) && (presProbX2v2 < 0.01)) { calls[callS] = NucleotideAlignmentConstants.GAP_DIPLOID_ALLELE; continue; } } if (totalCnt < minCount) { continue; //no data leave missing } if ((double) siteCnt[0][callS] / (double) totalCnt > majority) { if ((ob != Alignment.UNKNOWN_DIPLOID_ALLELE) && (ob != mj)) { calls[callS] = Alignment.UNKNOWN_DIPLOID_ALLELE; } else { // calls[callS] = mj; calls[callS] = AlignmentUtils.getDiploidValue(mj, mj); } } else if ((double) siteCnt[1][callS] / (double) totalCnt > majority) { if ((ob != Alignment.UNKNOWN_DIPLOID_ALLELE) && (ob != mn)) { calls[callS] = Alignment.UNKNOWN_DIPLOID_ALLELE; } else { // calls[callS] = mn; calls[callS] = AlignmentUtils.getDiploidValue(mn, mn); } } else if (callhets) { //byte[] snpValue = {mj, mn}; byte het = AlignmentUtils.getDiploidValue(mj, mn); //byte het = IUPACNucleotides.getDegerateSNPByteFromTwoSNPs(snpValue); calls[callS] = het; } } return calls; } private void initHapLengths(int startSite, int endSite) { matchInWin = new short[anchorAlignment.getSequenceCount()][anchorAlignment.getSequenceCount()]; diffInWin = new short[anchorAlignment.getSequenceCount()][anchorAlignment.getSequenceCount()]; // pOfMatch=new float[anchorAlignment.getSequenceCount()][anchorAlignment.getSequenceCount()]; // int currWord=initialSite>>6; int maxWord = anchorAlignment.getAllelePresenceForAllSites(0, 0).getNumWords() - 1; //int maxWord = anchorAlignment.getTaxaBitsNoClone(0, 0).getNumWords() - 1; int startWord = startSite >> 6; int endWord = endSite >> 6; if (endWord > maxWord) { endWord = maxWord; } // int startWord=(currWord-windowSize<0)?0:currWord-windowSize; // int endWord=(currWord+windowSize>=maxWord)?maxWord-1:currWord+windowSize; System.out.printf("Start Site:%d Word:%d End Site:%d Word:%d %n", startSite, startWord, endSite, endWord); // int[] bins=new int[101]; // int[] countClose=new int[anchorAlignment.getSequenceCount()]; for (int i = 0; i < anchorAlignment.getSequenceCount(); i++) { if (maskHighHets && highHet[i]) { continue; } long[] imj = anchorAlignment.getAllelePresenceForAllSites(i, 0).getBits(); //long[] imj = anchorAlignment.getTaxaBitsNoClone(i, 0).getBits(); long[] imn = anchorAlignment.getAllelePresenceForAllSites(i, 1).getBits(); //long[] imn = anchorAlignment.getTaxaBitsNoClone(i, 1).getBits(); for (int j = 0; j < i; j++) { if (maskHighHets && highHet[j]) { continue; } long[] jmj = anchorAlignment.getAllelePresenceForAllSites(j, 0).getBits(); //long[] jmj = anchorAlignment.getTaxaBitsNoClone(j, 0).getBits(); long[] jmn = anchorAlignment.getAllelePresenceForAllSites(j, 1).getBits(); //long[] jmn = anchorAlignment.getTaxaBitsNoClone(j, 1).getBits(); int same = 0, diff = 0, hets = 0; // int minorSame=0; for (int w = startWord; w <= endWord; w++) { long ihetMask = ~(imj[w] & imn[w]); long jhetMask = ~(jmj[w] & jmn[w]); long imjnh = imj[w] & ihetMask; long imnnh = imn[w] & ihetMask; long jmjnh = jmj[w] & jhetMask; long jmnnh = jmn[w] & jhetMask; same += Long.bitCount(imjnh & jmjnh) + Long.bitCount(imnnh & jmnnh); diff += Long.bitCount(imjnh & jmnnh) + Long.bitCount(imnnh & jmjnh); // same+=Long.bitCount(imj[w]&jmj[w])+Long.bitCount(imn[w]&jmn[w]); // diff+=Long.bitCount(imj[w]&jmn[w])+Long.bitCount(imn[w]&jmj[w]); // hets+=Long.bitCount(mj[w]&mn[w])+Long.bitCount(jmn[w]&jmj[w]); // minorSame+=Long.bitCount(imn[w]&jmn[w]); } // matchInWin[j][i]=matchInWin[i][j]=same; // diffInWin[j][i]=diffInWin[i][j]=diff; matchInWin[j][i] = matchInWin[i][j] = (short) (same - hets); diffInWin[j][i] = diffInWin[i][j] = (short) (diff - hets); // int sum=same+diff-(2*hets); // double div=(double)diffInWin[j][i]/(double)sum; // if((div<0.02)&&(sum>100)) { // countClose[i]++; // countClose[j]++; // if (div<0.03) System.out.printf("%s %s %d %d %d %g %n",anchorAlignment.getTaxaName(i),anchorAlignment.getTaxaName(j),matchInWin[j][i],diffInWin[j][i],sum, div); // bins[(int)((diff*100)/sum)]++; } } // for (int i = 0; i < bins.length; i++) { // System.out.printf("%d %d %d%n",initialSite,i,bins[i]); // for (int i = 0; i < countClose.length; i++) { // System.out.printf("%d %s %d%n",initialSite, anchorAlignment.getTaxaName(i),countClose[i]); } public void writeAlignment(String outfile) { ExportUtils.writeToHapmap(impAlign, false, outfile, '\t', null); } public static void main(String[] args) { System.out.println("Running main method in FastImputation"); String[] dargs = { // "-hmp", "/Users/edbuckler/SolexaAnal/GBS/build110813/test/maize110812.cov10.fT1E1pLD.mgNoHet.c10.hmp.txt", "-hmp","/Volumes/LaCie/GEM-DH_Production_January2012_FINAL_chr10.hmp.txt", // "-o", "/Users/edbuckler/SolexaAnal/GBS/build110813/test/maize110812.cov10.fT1E1pLD.mgNoHet.imp.c10.hmp.txt", "-o", "/Volumes/LaCie/GEM-DH_Production_January2012_FINAL_chr10.imp.hmp.txt", "sC", "10", "eC", "10" }; if (args.length == 0) { args = dargs; } int sC = Integer.parseInt(args[5]); int eC = Integer.parseInt(args[7]); String outfile, anchorMapFile; for (int cNum = sC; cNum <= eC; cNum++) { outfile = args[3].replace("+", "" + cNum); anchorMapFile = args[1].replace("+", "" + cNum); System.out.println("Reading " + anchorMapFile); Alignment a = ImportUtils.readFromHapmap(anchorMapFile, null); System.out.printf("Read Alignment with %d taxa and %d sites %n", a.getSequenceCount(), a.getSiteCount()); System.out.println("p1a:" + a.getBaseAsStringRow(1)); //a = TBitAlignment.getInstance(a); a = ConvertSBitTBitPlugin.convertAlignment(a, ConvertSBitTBitPlugin.CONVERT_TYPE.tbit, null); System.out.println("TBA:" + a.getBaseAsStringRow(1)); FastImputationBitFixedWindow fi = new FastImputationBitFixedWindow(a); System.out.println("Writing " + outfile); fi.writeAlignment(outfile); } } }
package nl.hannahsten.texifyidea.action.insert; import nl.hannahsten.texifyidea.TexifyIcons; import nl.hannahsten.texifyidea.action.InsertEditorAction; /** * @author Adam Williams */ public class InsertEmphasisAction extends InsertEditorAction { public InsertEmphasisAction() { super("Emphasis", null, "\\emph{", "}"); } }
/** * @author Amanda Fisher */ import java.util.ArrayList; /** * Contains the methods needed for a Protease who cuts before or after apecific proteins without any other conditions. Otherwise the method cut needs to be overwritten and new conditions added */ public class Protease { public ArrayList<Character> cutAminoAcids = new ArrayList<>(); public boolean cutsBefore;// does it cut before or after the proteins in cutAminoAcids /** * Cut array list. * * @param sequence the sequence * @return the array list * @throws ProteaseException the protease exception */ public ArrayList<String> cut(String sequence) throws ProteaseException { ArrayList<Character> buildingIons = new ArrayList<>(); ArrayList<String> cutSequence = new ArrayList<>(); sequence = checkSequence(sequence); //runs the sequence through the sequence checker method in order to detect any errors int i = 0; //needed to send what the character after the currentAA is for (Character currentAA : sequence.toCharArray()) { if (!cutsBefore) { buildingIons.add(currentAA); } for (Character currentCutPoint : cutAminoAcids) { //should make a new method for determing if the protease should cut here so that more a complex protease only has to override that smaller method instead of the larger cut method Character afterAA = ' '; if ((i + 1) <= (sequence.toCharArray().length - 1)) { afterAA = sequence.toCharArray()[i + 1]; } if (shouldCutHere(currentAA, currentCutPoint, afterAA)) { makeIon(buildingIons, cutSequence); } if (shouldCutHere(currentAA,currentCutPoint)){ makeIon(buildingIons,cutSequence); } } if (cutsBefore) { buildingIons.add(currentAA); } } return cutSequence; } public boolean shouldCutHere(Character currentAA,Character currentCutPoint) { boolean shouldCut = false; if (currentAA == currentCutPoint) { shouldCut = true; } return shouldCut; } public boolean shouldCutHere(Character currentAA, Character currentCutPoint, Character afterAA) { boolean shouldCut = false; if (currentAA == currentCutPoint) { shouldCut = true; } return shouldCut; } public String checkSequence(String sequence) throws ProteaseException { if (sequence.contains(" ")) { throw new ProteaseException("Sequence to be cut must not contain spaces."); } else if (sequence.matches(".*\\d.*")) { throw new ProteaseException("Sequence to be cut must not contain numbers."); } else if (sequence.matches(".*[a-z].*")) { throw new ProteaseException("Sequence to be cut must contain all upper case letters."); } return sequence; } /** * Takes the characters collected by cut and turns them in to a string that represents the sequence of the Ion * * @param buildingIons The current ion * @param cutSequence The sequence to be cut */ public void makeIon(ArrayList<Character> buildingIons, ArrayList<String> cutSequence) { String ion = new String(); for (Character c : buildingIons) { ion += c.toString(); } cutSequence.add(ion); buildingIons.clear(); } }
package nl.rubensten.texifyidea.highlighting; import com.intellij.lexer.Lexer; import com.intellij.openapi.editor.DefaultLanguageHighlighterColors; import com.intellij.openapi.editor.colors.TextAttributesKey; import com.intellij.openapi.fileTypes.SyntaxHighlighterBase; import com.intellij.psi.tree.IElementType; import nl.rubensten.texifyidea.LatexLexerAdapter; import nl.rubensten.texifyidea.psi.LatexTypes; import org.jetbrains.annotations.NotNull; /** * @author Ruben Schellekens, Sten Wessel */ public class LatexSyntaxHighlighter extends SyntaxHighlighterBase { /* * TextAttributesKeys */ public static final TextAttributesKey BRACES = TextAttributesKey.createTextAttributesKey( "LATEX_BRACES", DefaultLanguageHighlighterColors.BRACES ); public static final TextAttributesKey BRACKETS = TextAttributesKey.createTextAttributesKey( "LATEX_BRACKETS", DefaultLanguageHighlighterColors.BRACKETS ); public static final TextAttributesKey OPTIONAL_PARAM = TextAttributesKey.createTextAttributesKey( "LATEX_OPTIONAL_PARAM", DefaultLanguageHighlighterColors.PARAMETER ); public static final TextAttributesKey COMMAND = TextAttributesKey.createTextAttributesKey( "LATEX_COMMAND", DefaultLanguageHighlighterColors.KEYWORD ); public static final TextAttributesKey COMMAND_MATH_INLINE = TextAttributesKey.createTextAttributesKey( "LATEX_COMMAND_MATH_INLINE", DefaultLanguageHighlighterColors.VALID_STRING_ESCAPE ); public static final TextAttributesKey COMMAND_MATH_DISPLAY = TextAttributesKey .createTextAttributesKey( "LATEX_COMMAND_MATH_DISPLAY", DefaultLanguageHighlighterColors.VALID_STRING_ESCAPE ); public static final TextAttributesKey COMMENT = TextAttributesKey.createTextAttributesKey( "LATEX_COMMENT", DefaultLanguageHighlighterColors.LINE_COMMENT ); public static final TextAttributesKey INLINE_MATH = TextAttributesKey.createTextAttributesKey( "LATEX_INLINE_MATH", DefaultLanguageHighlighterColors.STRING ); public static final TextAttributesKey DISPLAY_MATH = TextAttributesKey.createTextAttributesKey( "LATEX_DISPLAY_MATH", DefaultLanguageHighlighterColors.STRING ); public static final TextAttributesKey STAR = TextAttributesKey.createTextAttributesKey( "LATEX_STAR", DefaultLanguageHighlighterColors.DOT ); /* * TextAttributeKey[]s */ private static final TextAttributesKey[] BRACES_KEYS = new TextAttributesKey[] { BRACES }; private static final TextAttributesKey[] BRACKET_KEYS = new TextAttributesKey[] { BRACKETS }; private static final TextAttributesKey[] COMMAND_KEYS = new TextAttributesKey[] { COMMAND }; private static final TextAttributesKey[] COMMENT_KEYS = new TextAttributesKey[] { COMMENT }; private static final TextAttributesKey[] INLINE_MATH_KEYS = new TextAttributesKey[] { INLINE_MATH }; private static final TextAttributesKey[] DISPLAY_MATH_KEYS = new TextAttributesKey[] { DISPLAY_MATH }; private static final TextAttributesKey[] STAR_KEYS = new TextAttributesKey[] { STAR }; private static final TextAttributesKey[] EMPTY_KEYS = new TextAttributesKey[0]; @NotNull @Override public Lexer getHighlightingLexer() { return new LatexLexerAdapter(); } @NotNull @Override public TextAttributesKey[] getTokenHighlights(IElementType tokenType) { // Braces if (tokenType.equals(LatexTypes.OPEN_BRACE) || tokenType.equals(LatexTypes.CLOSE_BRACE)) { return BRACES_KEYS; } // Brackets else if (tokenType.equals(LatexTypes.OPEN_BRACKET) || tokenType.equals(LatexTypes.CLOSE_BRACKET)) { return BRACKET_KEYS; } // Comments else if (tokenType.equals(LatexTypes.COMMENT_TOKEN)) { return COMMENT_KEYS; } // Commands else if (tokenType.equals(LatexTypes.COMMAND_TOKEN)) { return COMMAND_KEYS; } // Math environment else if (tokenType.equals(LatexTypes.INLINE_MATH_END) || tokenType.equals(LatexTypes.INLINE_MATH_END)) { return INLINE_MATH_KEYS; } else if (tokenType.equals(LatexTypes.DISPLAY_MATH_START) || tokenType.equals(LatexTypes.DISPLAY_MATH_END)) { return DISPLAY_MATH_KEYS; } // Star else if (tokenType.equals(LatexTypes.STAR)) { return STAR_KEYS; } // When no supported highlights is available else { return EMPTY_KEYS; } } }
package org.ensembl.healthcheck.testcase.generic; import java.sql.Connection; import java.util.Collection; import java.util.HashSet; import java.util.List; import java.util.Set; import org.ensembl.healthcheck.DatabaseRegistryEntry; import org.ensembl.healthcheck.ReportManager; import org.ensembl.healthcheck.Team; import org.ensembl.healthcheck.testcase.SingleDatabaseTestCase; import org.ensembl.healthcheck.util.DBUtils; import org.ensembl.healthcheck.util.SqlTemplate; /** * Healthcheck for the assembly_exception table. */ public class AssemblyExceptions extends SingleDatabaseTestCase { /** * Check the assembly_exception table. */ public AssemblyExceptions() { addToGroup("post_genebuild"); addToGroup("pre-compara-handover"); addToGroup("post-compara-handover"); setDescription("Check assembly_exception table"); setTeamResponsible(Team.GENEBUILD); addToGroup("compara-ancestral"); } /** * Check the data in the assembly_exception table. Note referential integrity checks are done in CoreForeignKeys. * * @param dbre * The database to use. * @return Result. */ public boolean run(DatabaseRegistryEntry dbre) { boolean result = true; result &= checkStartEnd(dbre); result &= seqMapping(dbre); return result; } private boolean seqMapping(DatabaseRegistryEntry dbre) { boolean result = false; SqlTemplate t = DBUtils.getSqlTemplate(dbre); Connection con = dbre.getConnection(); String all_sql = "SELECT distinct sr.name FROM seq_region sr, assembly_exception ax where ax.seq_region_id = sr.seq_region_id and exc_type not in ('PAR')"; List<String> all_exc = t.queryForDefaultObjectList(all_sql, String.class); String daf_sql = "SELECT distinct sr.name FROM seq_region sr, assembly_exception ax, dna_align_feature daf, analysis a " + " WHERE sr.seq_region_id = ax.seq_region_id AND exc_type not in ('HAP') AND sr.seq_region_id = daf.seq_region_id " + " AND daf.analysis_id = a.analysis_id AND a.logic_name = 'alt_seq_mapping'"; List<String> daf_exc = t.queryForDefaultObjectList(daf_sql, String.class); Set<String> missing = new HashSet<String>(all_exc); missing.removeAll(daf_exc); if(missing.isEmpty()) { result = true; } for(String name: missing) { String msg = String.format("Assembly exception '%s' does not have a sequence mapping", name); ReportManager.problem(this, dbre.getConnection(), msg); } return result; } private boolean checkStartEnd(DatabaseRegistryEntry dbre) { Connection con = dbre.getConnection(); boolean result = true; // check that seq_region_end > seq_region_start int rows = DBUtils.getRowCount(con, "SELECT COUNT(*) FROM assembly_exception WHERE seq_region_start > seq_region_end"); if (rows > 0) { result = false; ReportManager.problem(this, con, "assembly_exception has " + rows + " rows where seq_region_start > seq_region_end"); } // check that exc_seq_region_start > exc_seq_region_end rows = DBUtils.getRowCount(con, "SELECT COUNT(*) FROM assembly_exception WHERE exc_seq_region_start > exc_seq_region_end"); if (rows > 0) { result = false; ReportManager.problem(this, con, "assembly_exception has " + rows + " rows where exc_seq_region_start > exc_seq_region_end"); } // If the assembly_exception table contains an exception of type 'HAP' then // there should be at least one seq_region_attrib row of type 'non-reference' if (DBUtils.getRowCount(con, "SELECT COUNT(*) FROM assembly_exception WHERE exc_type='HAP'") > 0) { if (DBUtils.getRowCount(con, "SELECT COUNT(*) FROM seq_region_attrib sra, attrib_type at WHERE sra.attrib_type_id=at.attrib_type_id AND at.code='non_ref'") == 0) { result = false; ReportManager.problem(this, con, "assembly_exception contains at least one exception of type 'HAP' but there are no seq_region_attrib rows of type 'non-reference'"); } } if (result) { ReportManager.correct(this, con, "assembly_exception start/end co-ordinates make sense"); } return result; } } // AssemblyException
package org.ensembl.healthcheck.testcase.variation; import java.sql.Connection; import java.util.ArrayList; import java.util.List; import org.ensembl.healthcheck.DatabaseRegistry; import org.ensembl.healthcheck.DatabaseRegistryEntry; import org.ensembl.healthcheck.DatabaseType; import org.ensembl.healthcheck.ReportManager; import org.ensembl.healthcheck.Species; import org.ensembl.healthcheck.Team; import org.ensembl.healthcheck.testcase.MultiDatabaseTestCase; import org.ensembl.healthcheck.util.DBUtils; /** * An EnsEMBL Healthcheck test case that looks for broken foreign-key * relationships between core and variation database. */ public class ForeignKeyCoreId extends MultiDatabaseTestCase { /** * Create an ForeignKeyCoreId that applies to a specific set of databases. */ public ForeignKeyCoreId() { addToGroup("variation"); addToGroup("variation-release"); setDescription("Check for broken foreign-key relationships between variation and core databases."); setHintLongRunning(true); setTeamResponsible(Team.VARIATION); } /** * Run the test. * * @param databases * The databases to check, in order core->variation * @return true if same transcripts and seq_regions in core and variation * are the same. * */ public boolean run(DatabaseRegistry dbr) { boolean overallResult = true; DatabaseRegistryEntry[] variationDBs = dbr .getAll(DatabaseType.VARIATION); // the database registry parameter dbr only contains the databases // matching the regular expression passed on the command line // so create a database registry containing all the core databases and // find the one we want List<String> coreRegexps = new ArrayList<String>(); coreRegexps.add(".*_core_.*"); DatabaseRegistry allDBR = new DatabaseRegistry(coreRegexps, null, null, false); for (int i = 0; i < variationDBs.length; i++) { boolean result = true; DatabaseRegistryEntry dbrvar = variationDBs[i]; Connection con = dbrvar.getConnection(); try { Species species = dbrvar.getSpecies(); String variationName = dbrvar.getName(); String coreName = variationName.replaceAll("variation", "core"); DatabaseRegistryEntry dbrcore = allDBR.getByExactName(coreName); if (dbrcore == null) { logger.severe("Incorrect core database " + coreName + " for " + variationName); throw new Exception("Incorrect core database " + coreName + " for " + variationName); } ReportManager.info(this, con, "Using " + dbrcore.getName() + " as core database and " + dbrvar.getName() + " as variation database"); result &= checkForOrphans(con, dbrvar.getName() + ".transcript_variation", "feature_stable_id", dbrcore.getName() + ".transcript", "stable_id"); result &= checkForOrphansWithConstraint(con, dbrvar.getName() + ".variation_feature", "seq_region_id", dbrcore.getName() + ".seq_region", "seq_region_id", "seq_region_id IS NOT NULL"); result &= checkForOrphansWithConstraint(con, dbrvar.getName() + ".read_coverage", "seq_region_id", dbrcore.getName() + ".seq_region", "seq_region_id", "seq_region_id IS NOT NULL"); result &= checkForOrphansWithConstraint(con, dbrvar.getName() + ".structural_variation_feature", "seq_region_id", dbrcore.getName() + ".seq_region", "seq_region_id", "seq_region_id IS NOT NULL"); int rows = DBUtils .getRowCount( con, "SELECT COUNT(*) FROM " + dbrvar.getName() + ".seq_region srv ," + dbrcore.getName() + ".seq_region src," + dbrcore.getName() + ".coord_system cs WHERE cs.attrib = 'default_version' AND cs.coord_system_id = src.coord_system_id AND src.name=srv.name AND src.seq_region_id != srv.seq_region_id"); if (rows > 0) { ReportManager .problem( this, con, rows + " rows seq_region in core has same name, but different seq_region_id comparing with seq_region in variation database"); result = false; } if (result) { // if there were no problems, just inform for the interface // to pick the HC ReportManager.correct(this, con, "ForeignKeyCoreId test passed without any problem"); } } catch (Exception e) { ReportManager .problem( this, con, "HealthCheck generated an exception: " + e.getMessage()); result = false; } overallResult &= result; } return overallResult; } /** * This only applies to variation databases. */ public void types() { removeAppliesToType(DatabaseType.OTHERFEATURES); removeAppliesToType(DatabaseType.CDNA); removeAppliesToType(DatabaseType.CORE); removeAppliesToType(DatabaseType.VEGA); } } // ForeignKeyCoreId
package org.pentaho.di.trans.steps.scriptvalues_mod; import java.math.BigDecimal; import java.util.Date; import java.util.Hashtable; import java.util.Map; import org.mozilla.javascript.Context; import org.mozilla.javascript.EvaluatorException; import org.mozilla.javascript.Script; import org.mozilla.javascript.Scriptable; import org.mozilla.javascript.ScriptableObject; import org.pentaho.di.compatibility.Row; import org.pentaho.di.compatibility.Value; import org.pentaho.di.compatibility.ValueUsedListener; import org.pentaho.di.core.Const; import org.pentaho.di.core.exception.KettleException; import org.pentaho.di.core.exception.KettleValueException; import org.pentaho.di.core.row.RowDataUtil; import org.pentaho.di.core.row.RowMeta; import org.pentaho.di.core.row.RowMetaInterface; import org.pentaho.di.core.row.ValueDataUtil; import org.pentaho.di.core.row.ValueMetaInterface; import org.pentaho.di.core.xml.XMLHandler; import org.pentaho.di.trans.Trans; import org.pentaho.di.trans.TransMeta; import org.pentaho.di.trans.step.BaseStep; import org.pentaho.di.trans.step.StepDataInterface; import org.pentaho.di.trans.step.StepInterface; import org.pentaho.di.trans.step.StepMeta; import org.pentaho.di.trans.step.StepMetaInterface; /** * Executes a JavaScript on the values in the input stream. * Selected calculated values can then be put on the output stream. * * @author Matt * @since 5-April-2003 */ public class ScriptValuesMod extends BaseStep implements StepInterface, ScriptValuesModInterface { private ScriptValuesMetaMod meta; private ScriptValuesModData data; public final static int SKIP_TRANSFORMATION = 1; public final static int ABORT_TRANSFORMATION = -1; public final static int ERROR_TRANSFORMATION = -2; public final static int CONTINUE_TRANSFORMATION = 0; private static boolean bWithTransStat = false; private static boolean bRC = false; private static int iTranStat = CONTINUE_TRANSFORMATION; private boolean bFirstRun = false; private ScriptValuesScript[] jsScripts; private String strTransformScript=""; private String strStartScript=""; private String strEndScript=""; // public static Row insertRow; public static Script script; public ScriptValuesMod(StepMeta stepMeta, StepDataInterface stepDataInterface, int copyNr, TransMeta transMeta, Trans trans){ super(stepMeta, stepDataInterface, copyNr, transMeta, trans); } private void determineUsedFields(RowMetaInterface row){ int nr=0; // Count the occurrences of the values. // Perhaps we find values in comments, but we take no risk! for (int i=0;i<row.size();i++){ String valname = row.getValueMeta(i).getName().toUpperCase(); if (strTransformScript.toUpperCase().indexOf(valname)>=0){ nr++; } } // Allocate fields_used data.fields_used = new int[nr]; data.values_used = new Value[nr]; nr = 0; // Count the occurrences of the values. // Perhaps we find values in comments, but we take no risk! for (int i=0;i<row.size();i++){ // Values are case-insensitive in JavaScript. String valname = row.getValueMeta(i).getName(); if (strTransformScript.indexOf(valname)>=0){ if (log.isDetailed()) logDetailed(Messages.getString("ScriptValuesMod.Log.UsedValueName",String.valueOf(i),valname)); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ data.fields_used[nr]=i; nr++; } } if (log.isDetailed()) logDetailed(Messages.getString("ScriptValuesMod.Log.UsingValuesFromInputStream",String.valueOf(data.fields_used.length))); //$NON-NLS-1$ //$NON-NLS-2$ } private boolean addValues(RowMetaInterface rowMeta, Object[] row) throws KettleValueException { if (first) { first = false; // What is the output row looking like? data.outputRowMeta = getInputRowMeta().clone(); meta.getFields(data.outputRowMeta, getStepname(), null, null, this); // Determine the indexes of the fields used! determineUsedFields(rowMeta); data.cx = Context.enter(); data.cx.setOptimizationLevel(9); data.scope = data.cx.initStandardObjects(null, true); bFirstRun = true; Scriptable jsvalue = Context.toObject(this, data.scope); data.scope.put("_step_", data.scope, jsvalue); //$NON-NLS-1$ // Adding the existing Scripts to the Context for (int i = 0; i < meta.getNumberOfJSScripts(); i++) { Scriptable jsR = Context.toObject(jsScripts[i].getScript(), data.scope); data.scope.put(jsScripts[i].getScriptName(), data.scope, jsR); } // Adding the Name of the Transformation to the Context data.scope.put("_TransformationName_", data.scope, this.getName()); try { // add these now (they will be re-added later) to make compilation succeed // Add the old style row object for compatibility reasons... if (meta.isCompatible()) { Row v2Row = RowMeta.createOriginalRow(rowMeta, row); Scriptable jsV2Row = Context.toObject(v2Row, data.scope); data.scope.put("row", data.scope, jsV2Row); //$NON-NLS-1$ } else { Scriptable jsrow = Context.toObject(row, data.scope); data.scope.put("row", data.scope, jsrow); //$NON-NLS-1$ } // Add the used fields... for (int i = 0; i < data.fields_used.length; i++) { ValueMetaInterface valueMeta = rowMeta.getValueMeta(data.fields_used[i]); Object valueData = row[data.fields_used[i]]; if (meta.isCompatible()) { data.values_used[i] = valueMeta.createOriginalValue(valueData); Scriptable jsarg = Context.toObject(data.values_used[i], data.scope); data.scope.put(valueMeta.getName(), data.scope, jsarg); } else { Scriptable jsarg; if (valueData!=null) { jsarg = Context.toObject(valueData, data.scope); } else { jsarg = null; } data.scope.put(valueMeta.getName(), data.scope, jsarg); } } // also add the meta information for the hole row Scriptable jsrowMeta = Context.toObject(rowMeta, data.scope); data.scope.put("rowMeta", data.scope, jsrowMeta); //$NON-NLS-1$ // Modification for Additional Script parsing try { if (meta.getAddClasses() != null) { for (int i = 0; i < meta.getAddClasses().length; i++) { Object jsOut = Context.javaToJS(meta.getAddClasses()[i].getAddObject(), data.scope); ScriptableObject.putProperty(data.scope, meta.getAddClasses()[i].getJSName(), jsOut); } } } catch (Exception e) { throw new KettleValueException(Messages.getString("ScriptValuesMod.Log.CouldNotAttachAdditionalScripts"), e); //$NON-NLS-1$ } // Adding some default JavaScriptFunctions to the System try { Context.javaToJS(ScriptValuesAddedFunctions.class, data.scope); ((ScriptableObject) data.scope).defineFunctionProperties(ScriptValuesAddedFunctions.jsFunctionList, ScriptValuesAddedFunctions.class, ScriptableObject.DONTENUM); } catch (Exception ex) { // System.out.println(ex.toString()); throw new KettleValueException(Messages.getString("ScriptValuesMod.Log.CouldNotAddDefaultFunctions"), ex); //$NON-NLS-1$ } ; // Adding some Constants to the JavaScript try { data.scope.put("SKIP_TRANSFORMATION", data.scope, Integer.valueOf(SKIP_TRANSFORMATION)); data.scope.put("ABORT_TRANSFORMATION", data.scope, Integer.valueOf(ABORT_TRANSFORMATION)); data.scope.put("ERROR_TRANSFORMATION", data.scope, Integer.valueOf(ERROR_TRANSFORMATION)); data.scope.put("CONTINUE_TRANSFORMATION", data.scope, Integer.valueOf(CONTINUE_TRANSFORMATION)); } catch (Exception ex) { // System.out.println("Exception Adding the Constants " + ex.toString()); throw new KettleValueException(Messages.getString("ScriptValuesMod.Log.CouldNotAddDefaultConstants"), ex); } ; try { // Checking for StartScript if (strStartScript != null && strStartScript.length() > 0) { Script startScript = data.cx.compileString(strStartScript, "trans_Start", 1, null); startScript.exec(data.cx, data.scope); if (log.isDetailed()) logDetailed(("Start Script found!")); } else { if (log.isDetailed()) logDetailed(("No starting Script found!")); } } catch (Exception es) { // System.out.println("Exception processing StartScript " + es.toString()); throw new KettleValueException(Messages.getString("ScriptValuesMod.Log.ErrorProcessingStartScript"), es); } // Now Compile our Script data.script = data.cx.compileString(strTransformScript, "script", 1, null); } catch (Exception e) { throw new KettleValueException(Messages.getString("ScriptValuesMod.Log.CouldNotCompileJavascript"), e); } } // Filling the defined TranVars with the Values from the Row Object[] outputRow = RowDataUtil.resizeArray(row, rowMeta.size() + meta.getName().length); // Keep an index... int outputIndex = rowMeta.size(); // Keep track of the changed values... final Map<Integer, Value> usedRowValues; if (meta.isCompatible()) { usedRowValues = new Hashtable<Integer, Value>(); } else { usedRowValues = null; } try { try { if (meta.isCompatible()) { Row v2Row = RowMeta.createOriginalRow(rowMeta, row); Scriptable jsV2Row = Context.toObject(v2Row, data.scope); data.scope.put("row", data.scope, jsV2Row); //$NON-NLS-1$ v2Row.getUsedValueListeners().add(new ValueUsedListener() { public void valueIsUsed(int index, Value value) { usedRowValues.put(index, value); } } ); } else { Scriptable jsrow = Context.toObject(row, data.scope); data.scope.put("row", data.scope, jsrow); //$NON-NLS-1$ } for (int i = 0; i < data.fields_used.length; i++) { ValueMetaInterface valueMeta = rowMeta.getValueMeta(data.fields_used[i]); Object valueData = row[data.fields_used[i]]; if (meta.isCompatible()) { data.values_used[i] = valueMeta.createOriginalValue(valueData); Scriptable jsarg = Context.toObject(data.values_used[i], data.scope); data.scope.put(valueMeta.getName(), data.scope, jsarg); } else { Scriptable jsarg; if (valueData!=null) { jsarg = Context.toObject(valueData, data.scope); } else { jsarg = null; } data.scope.put(valueMeta.getName(), data.scope, jsarg); } } // also add the meta information for the hole row Scriptable jsrowMeta = Context.toObject(rowMeta, data.scope); data.scope.put("rowMeta", data.scope, jsrowMeta); //$NON-NLS-1$ } catch (Exception e) { throw new KettleValueException(Messages.getString("ScriptValuesMod.Log.UnexpectedeError"), e); //$NON-NLS-1$ //$NON-NLS-2$ } // Executing our Script data.script.exec(data.cx, data.scope); if (bFirstRun) { bFirstRun = false; // Check if we had a Transformation Status Object tran_stat = data.scope.get("trans_Status", data.scope); if (tran_stat != ScriptableObject.NOT_FOUND) { bWithTransStat = true; if (log.isDetailed()) logDetailed(("tran_Status found. Checking transformation status while script execution.")); //$NON-NLS-1$ //$NON-NLS-2$ } else { if (log.isDetailed()) logDetailed(("No tran_Status found. Transformation status checking not available.")); //$NON-NLS-1$ //$NON-NLS-2$ bWithTransStat = false; } } if (bWithTransStat) { iTranStat = (int) Context.toNumber(data.scope.get("trans_Status", data.scope)); } else { iTranStat = CONTINUE_TRANSFORMATION; } if (iTranStat == CONTINUE_TRANSFORMATION) { bRC=true; for (int i = 0; i < meta.getName().length; i++) { Object result = data.scope.get(meta.getName()[i], data.scope); outputRow[outputIndex]= getValueFromJScript(result, i); outputIndex++; } // Also modify the "in-place" value changes: // --> the field.trim() type of changes... // As such we overwrite all the used fields again. if (meta.isCompatible()) { for (int i = 0 ; i < data.values_used.length ; i++) { ValueMetaInterface valueMeta = rowMeta.getValueMeta(data.fields_used[i]); outputRow[data.fields_used[i]] = valueMeta.getValueData(data.values_used[i]); } // Grab the variables in the "row" object too. for (Integer index : usedRowValues.keySet()) { Value value = usedRowValues.get(index); ValueMetaInterface valueMeta = rowMeta.getValueMeta(index); outputRow[index] = valueMeta.getValueData(value); } } putRow(data.outputRowMeta, outputRow); } else { switch (iTranStat) { case SKIP_TRANSFORMATION: // eat this row. bRC = true; break; case ABORT_TRANSFORMATION: if (data.cx!=null) Context.exit(); stopAll(); setOutputDone(); bRC = false; break; case ERROR_TRANSFORMATION: if (data.cx!=null) Context.exit(); setErrors(1); stopAll(); bRC = false; break; } // TODO: kick this "ERROR handling" junk out now that we have solid error handling in place. } } catch (Exception e) { throw new KettleValueException(Messages.getString("ScriptValuesMod.Log.JavascriptError"), e); //$NON-NLS-1$ } return bRC; } public Object getValueFromJScript(Object result, int i) throws KettleValueException { if (meta.getName()[i] != null && meta.getName()[i].length() > 0) { // res.setName(meta.getRename()[i]); // res.setType(meta.getType()[i]); try { if (result != null) { String classType = result.getClass().getName(); switch (meta.getType()[i]) { case ValueMetaInterface.TYPE_NUMBER: if (classType.equalsIgnoreCase("org.mozilla.javascript.Undefined")) { return null; } else if (classType.equalsIgnoreCase("org.mozilla.javascript.NativeJavaObject")) { try { // Is it a java Value class ? Value v = (Value) Context.jsToJava(result, Value.class); return v.getNumber(); } catch(Exception e) { String string = Context.toString(result); return new Double( Double.parseDouble(ValueDataUtil.trim(string)) ); } } else { Number nb = (Number) result; return new Double( nb.doubleValue() ); } case ValueMetaInterface.TYPE_INTEGER: if (classType.equalsIgnoreCase("java.lang.Byte")) { return new Long(((java.lang.Byte) result).longValue()); } else if (classType.equalsIgnoreCase("java.lang.Short")) { return new Long(((Short) result).longValue()); } else if (classType.equalsIgnoreCase("java.lang.Integer")) { return new Long(((Integer) result).longValue()); } else if (classType.equalsIgnoreCase("java.lang.Long")) { return new Long(((Long) result).longValue()); } else if (classType.equalsIgnoreCase("java.lang.Double")) { return new Long(((Double) result).longValue()); } else if (classType.equalsIgnoreCase("java.lang.String")) { return new Long((new Long((String) result)).longValue()); } else if (classType.equalsIgnoreCase("org.mozilla.javascript.Undefined")) { return null; } else if (classType.equalsIgnoreCase("org.mozilla.javascript.NativeJavaObject")) { // Is it a Value? try { Value value = (Value) Context.jsToJava(result, Value.class); return value.getInteger(); } catch (Exception e2) { String string = Context.toString(result); return new Long(Long.parseLong(ValueDataUtil.trim(string))); } } else { return new Long((long) ((Long) result).longValue()); } case ValueMetaInterface.TYPE_STRING: if (classType.equalsIgnoreCase("org.mozilla.javascript.NativeJavaObject") || //$NON-NLS-1$ classType.equalsIgnoreCase("org.mozilla.javascript.Undefined")) { // Is it a java Value class ? try { Value v = (Value) Context.jsToJava(result, Value.class); return v.toString(); } catch (Exception ev) { // convert to a string should work in most cases... String string = (String) Context.toString(result); return string; } } else { // A String perhaps? String string = (String) Context.toString(result); return string; } case ValueMetaInterface.TYPE_DATE: double dbl = 0; if (classType.equalsIgnoreCase("org.mozilla.javascript.Undefined")) { return null; } else { if (classType.equalsIgnoreCase("org.mozilla.javascript.NativeDate")) { dbl = Context.toNumber(result); } else if (classType.equalsIgnoreCase("org.mozilla.javascript.NativeJavaObject") || classType.equalsIgnoreCase("java.util.Date")) { // Is it a java Date() class ? try { Date dat = (Date) Context.jsToJava(result, java.util.Date.class); dbl = dat.getTime(); } catch (Exception e) { // Is it a Value? try { Value value = (Value)Context.jsToJava(result, Value.class); return value.getDate(); } catch(Exception e2) { try { String string = (String) Context.toString(result); return XMLHandler.stringToDate(string); } catch(Exception e3) { throw new KettleValueException("Can't convert a string to a date"); } } } } else if (classType.equalsIgnoreCase("java.lang.Double")) { dbl = ((Double) result).doubleValue(); } else { String string = (String) Context.jsToJava(result, String.class); dbl = Double.parseDouble(string); } long lng = Math.round(dbl); Date dat = new Date(lng); return dat; } case ValueMetaInterface.TYPE_BOOLEAN: return (Boolean)result; case ValueMetaInterface.TYPE_BIGNUMBER: if (classType.equalsIgnoreCase("org.mozilla.javascript.Undefined")) { return null; } else if (classType.equalsIgnoreCase("org.mozilla.javascript.NativeJavaObject")) { // Is it a BigDecimal class ? try { BigDecimal bd = (BigDecimal) Context.jsToJava(result, BigDecimal.class); return bd; } catch (Exception e) { try { Value v = (Value) Context.jsToJava(result, Value.class); if (!v.isNull()) return v.getBigNumber(); else return null; } catch(Exception e2) { String string = (String) Context.jsToJava(result, String.class); return new BigDecimal(string); } } } else if (classType.equalsIgnoreCase("java.lang.Byte")) { return new BigDecimal(((java.lang.Byte) result).longValue()); } else if (classType.equalsIgnoreCase("java.lang.Short")) { return new BigDecimal(((Short) result).longValue()); } else if (classType.equalsIgnoreCase("java.lang.Integer")) { return new BigDecimal(((Integer) result).longValue()); } else if (classType.equalsIgnoreCase("java.lang.Long")) { return new BigDecimal(((Long) result).longValue()); } else if (classType.equalsIgnoreCase("java.lang.Double")) { return new BigDecimal(((Double) result).longValue()); } else if (classType.equalsIgnoreCase("java.lang.String")) { return new BigDecimal((new Long((String) result)).longValue()); } else { throw new RuntimeException("JavaScript conversion to BigNumber not implemented for "+classType); } case ValueMetaInterface.TYPE_BINARY: { return Context.jsToJava(result, byte[].class); } default: throw new RuntimeException("JavaScript conversion not implemented for type" + meta.getType()[i]); } } else { return null; } } catch (Exception e) { throw new KettleValueException(Messages.getString("ScriptValuesMod.Log.JavascriptError"), e); //$NON-NLS-1$ } } else { throw new KettleValueException("No name was specified for result value } } public RowMetaInterface getOutputRowMeta() { return data.outputRowMeta; } public boolean processRow(StepMetaInterface smi, StepDataInterface sdi) throws KettleException{ meta=(ScriptValuesMetaMod)smi; data=(ScriptValuesModData)sdi; Object[] r=getRow(); // Get row from input rowset & set row busy! if (r==null) { //Modification for Additional End Function try{ // Checking for EndScript if(strEndScript != null && strEndScript.length()>0){ Script endScript = data.cx.compileString(strEndScript, "trans_End", 1, null); endScript.exec(data.cx, data.scope); if (log.isDetailed()) logDetailed(("End Script found!")); }else{ if (log.isDetailed()) logDetailed(("No end Script found!")); } }catch(Exception e){ logError(Messages.getString("ScriptValuesMod.Log.UnexpectedeError")+" : "+e.toString()); //$NON-NLS-1$ //$NON-NLS-2$ logError(Messages.getString("ScriptValuesMod.Log.ErrorStackTrace")+Const.CR+Const.getStackTracker(e)); //$NON-NLS-1$ setErrors(1); stopAll(); } if (data.cx!=null) Context.exit(); setOutputDone(); return false; } // Getting the Row, with the Transformation Status try { addValues(getInputRowMeta(), r); } catch(KettleValueException e) { String location = null; if (e.getCause() instanceof EvaluatorException) { EvaluatorException ee = (EvaluatorException) e.getCause(); location = "--> " + ee.lineNumber() + ":"+ ee.columnNumber(); // $NON-NLS-1$ $NON-NLS-2$ } if (getStepMeta().isDoingErrorHandling()) { putError(getInputRowMeta(), r, 1, e.getMessage()+Const.CR+location, null, "SCR-001"); } else { throw(e); } } if (checkFeedback(linesRead)) logBasic(Messages.getString("ScriptValuesMod.Log.LineNumber")+linesRead); //$NON-NLS-1$ return bRC; } public boolean init(StepMetaInterface smi, StepDataInterface sdi){ meta=(ScriptValuesMetaMod)smi; data=(ScriptValuesModData)sdi; if (super.init(smi, sdi)){ // Add init code here. // Get the actual Scripts from our MetaData jsScripts = meta.getJSScripts(); for(int j=0;j<jsScripts.length;j++){ switch(jsScripts[j].getScriptType()){ case ScriptValuesScript.TRANSFORM_SCRIPT: strTransformScript =jsScripts[j].getScript(); break; case ScriptValuesScript.START_SCRIPT: strStartScript =jsScripts[j].getScript(); break; case ScriptValuesScript.END_SCRIPT: strEndScript = jsScripts[j].getScript(); break; } } return true; } return false; } // Run is were the action happens! public void run() { try { logBasic(Messages.getString("System.Log.StartingToRun")); //$NON-NLS-1$ while (processRow(meta, data) && !isStopped()); } catch(Throwable t) { try { if (data.cx!=null) Context.exit(); } catch(Exception er) {}; logError(Messages.getString("System.Log.UnexpectedError")+" : "); //$NON-NLS-1$ //$NON-NLS-2$ logError(Const.getStackTracker(t)); setErrors(1); stopAll(); } finally { dispose(meta, data); logSummary(); markStop(); } } }